Итак, представим, что у нас есть уже готовое php+mysql приложение. Для начала регистрируемся . На почту придет письмо с подтверждением регистрации. Далее переходим по ссылке, вводим пароль и подтверждение, жмем save. Первый этап пройден, идем дальше.

После успешной регистрации сервис предлагает нам скачать клиент. Естественно, для каждой ОСи свой вариант установки. Далее будем рассматривать пример для UNIX.

Пишем в консоли:

Wget -qO- https://toolbelt.heroku.com/install.sh | sh

С установкой не должно возникнуть проблем. Также нам необходим установленный и настроенный git, об этом я писать не буду, на просторах интернета полно информации об этом.

После установки нужно войти в приложение:

$ heroku login

Вводим email и пароль. Приложение должно вас авторизовать и автоматически загрузить ваш публичный ssh ключ. Если этого не произошло, заходим в свой аккаунт (https://dashboard.heroku.com/account) и добавляем публичный ssh:

Чтобы посмотреть публичный ssh, пишем в консоли:

$ cat ~/.ssh/id_rsa.pub

Ключи также можно добавить с помощью команды:

$ heroku keys:add

Итак, все готово для того, чтобы создать свое первое «heroku приложение». Заходим в директорию, где хранится наше приложение, и пишем в консоли:

$ heroku create

В результате вы должны увидеть что-то похоже на это:

$ git push heroku master

После чего пишем в консоли:

$ heroku open

Наш сайт откроется в браузере. Если бы мы не юзали mysql, то на этом все бы и закончилось, но нам придется еще чуть попотеть. Скорее всего, на экране полезли ошибки о том, что невозможно соединиться с mysql. Также ошибки можно посмотреть, открыв логи:

$ heroku logs

Для работы с mysql будем использовать аддон ClearDB . Чтобы его установить, для начала необходимо заполнить данные о вашей кредитной карте на странице dashboard.heroku.com/account :

Если этого не сделать, при установке ClearDB вы будете видеть ошибку:

Adding cleardb:ignite on dry-taiga-2649... failed
! Please verify your account to install this add-on
! For more information, see devcenter.heroku.com/categories/billing
! Verify now at heroku.com/verify

Ниже команда для установки ClearDB:

$ heroku addons:add cleardb:ignite в

ClearDB установлен, теперь посмотрим доступы к базе данных:

$ heroku config

Получим результат в виде:

CLEARDB_DATABASE_URL:mysql://USER:PASSWORD@HOSTNAME/DBASENAME?reconnect=true

Используя полученные доступы через любой удобный MySQL клиент заливаем дамп БД на сервер.

Доступы к базе в php можно получить следующим образом:

$url=parse_url(getenv("CLEARDB_DATABASE_URL")); $server = $url["host"]; $username = $url["user"]; $password = $url["pass"]; $db = substr($url["path"],1); mysqli_connect($server, $username, $password); mysqli_select_db($db);

Чтобы каждый раз не менять конфиг для локального сайта и heroku, можно добавить проверку:

If ($_SERVER["SERVER_NAME"] == "thawing-island-242342379.herokuapp.com") { $url = parse_url(getenv("CLEARDB_DATABASE_URL")); $host = $url["host"]; $username = $url["user"]; $password = $url["pass"]; $dbname = substr($url["path"], 1); } else { $host = "localhost"; $dbname = "db"; $username = "user"; $password = "123"; }

Было бы правильней это сделать через APPLICATION_ENV, но я не нашел информации о том, как это сделать. Если кто-то в курсе - напишите.

Почти все готово. Осталось добавить в корень файл composer.json:

{ "require": { "ext-mysql": "*" } }

Если такой уже есть, нужно просто дописать "ext-mysql": "*"

Пишем в консоли:

$ git add . $ git commit -am "added db credentials" $ git push heroku master $ heroku open

Открывается браузер, видим рабочий сайт.

Буду рад если этот «мануал» кому то поможет.

Всем спасибо з а внимание.

Процесс создания системы регистрации – это довольно большой объем работы. Вам нужно написать код, который бы перепроверял валидность email-адресов, высылал email-письма с подтверждением, предлагал возможность восстановить пароль, хранил бы пароли в безопасном месте, проверял формы ввода и многое другое. Даже когда вы все это сделаете, пользователи будут регистрироваться неохотно, так как даже самая минимальная регистрация требует их активности.

В сегодняшнем руководстве мы займемся разработкой простой системы регистрации, с использованием которой вам не понадобятся никакие пароли! В результаты мы получим, систему, которую можно будет без труда изменить или встроить в существующий PHP-сайт. Если вам интересно, продолжайте чтение.

PHP

Теперь мы готовы к тому, чтобы заняться кодом PHP. Основной функционал системы регистрации предоставляется классом User, который вы можете видеть ниже. Класс использует (), представляющую собой минималистскую библиотеку для работы с базами данных. Класс User отвечает за доступ к базам данных, генерирование token-ов для логина и их валидации. Он представляет нам простой интерфейс, который можно без труда включить в систему регистрации на ваших сайтах, основанных на PHP.

User.class.php

// Private ORM instance
private $orm;

/**
* Find a user by a token string. Only valid tokens are taken into
* consideration. A token is valid for 10 minutes after it has been generated.
* @param string $token The token to search for
* @return User
*/

Public static function findByToken($token){

// find it in the database and make sure the timestamp is correct


->where("token", $token)
->where_raw("token_validity > NOW()")
->find_one();

If(!$result){
return false;
}

Return new User($result);
}

/**
* Either login or register a user.
* @return User
*/

Public static function loginOrRegister($email){

// If such a user already exists, return it

If(User::exists($email)){
return new User($email);
}

// Otherwise, create it and return it

Return User::create($email);
}

/**
* Create a new user and save it to the database
* @param string $email The user"s email address
* @return User
*/

Private static function create($email){

// Write a new user to the database and return it

$result = ORM::for_table("reg_users")->create();
$result->email = $email;
$result->save();

Return new User($result);
}

/**
* Check whether such a user exists in the database and return a boolean.
* @param string $email The user"s email address
* @return boolean
*/

Public static function exists($email){

// Does the user exist in the database?
$result = ORM::for_table("reg_users")
->where("email", $email)
->count();

Return $result == 1;
}

/**
* Create a new user object
* @param $param ORM instance, id, email or null
* @return User
*/

Public function __construct($param = null){

If($param instanceof ORM){

// An ORM instance was passed
$this->orm = $param;
}
else if(is_string($param)){

// An email was passed
$this->
->where("email", $param)
->find_one();
}
else{

If(is_numeric($param)){
// A user id was passed as a parameter
$id = $param;
}
else if(isset($_SESSION["loginid"])){

// No user ID was passed, look into the sesion
$id = $_SESSION["loginid"];
}

$this->orm = ORM::for_table("reg_users")
->where("id", $id)
->find_one();
}

/**
* Generates a new SHA1 login token, writes it to the database and returns it.
* @return string
*/

Public function generateToken(){
// generate a token for the logged in user. Save it to the database.

$token = sha1($this->email.time().rand(0, 1000000));

// Save the token to the database,
// and mark it as valid for the next 10 minutes only

$this->orm->set("token", $token);
$this->orm->set_expr("token_validity", "ADDTIME(NOW(),"0:10")");
$this->orm->save();

Return $token;
}

/**
* Login this user
* @return void
*/

Public function login(){

// Mark the user as logged in
$_SESSION["loginid"] = $this->orm->id;

// Update the last_login db field
$this->orm->set_expr("last_login", "NOW()");
$this->orm->save();
}

/**
* Destroy the session and logout the user.
* @return void
*/

Public function logout(){
$_SESSION = array();
unset($_SESSION);
}

/**
* Check whether the user is logged in.
* @return boolean
*/

Public function loggedIn(){
return isset($this->orm->id) && $_SESSION["loginid"] == $this->orm->id;
}

/**
* Check whether the user is an administrator
* @return boolean
*/

Public function isAdmin(){
return $this->rank() == "administrator";
}

/**
* Find the type of user. It can be either admin or regular.
* @return string
*/

Public function rank(){
if($this->orm->rank == 1){
return "administrator";
}

Return "regular";
}

/**
* Magic method for accessing the elements of the private
* $orm instance as properties of the user object
* @param string $key The accessed property"s name
* @return mixed
*/

Public function __get($key){
if(isset($this->orm->$key)){
return $this->orm->$key;
}

Return null;
}
}
Token-ы генерируются при помощи алгоритма , и сохраняются в базу данных. Мы используем из MySQL для установки значения в колонку token_validity, равного 10 минутам. При валидации token, мы сообщаем движку, что нам нужен token, поле token_validity пока еще не истекло. Таким образом мы ограничиваем время, в течение которого token будет валиден.

Обратите внимание на то, что мы используем волшебный метод __get () в конце документа, чтобы получить доступ к свойствам объекта user. Это позволяет нам осуществить доступ к данным, которые хранятся в базе данных в виде свойств: $user->email, $user->token. Для примера давайте посмотрим, как мы можем использовать этот класс в следующем фрагменте кода:


Еще один файл, в котором хранится необходимый функционал, это functions.php. Там у нас есть несколько вспомогательных функций, которые позволяют нам сохранить остальной код более опрятным.

Functions.php

Function send_email($from, $to, $subject, $message){

// Helper function for sending email

$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type: text/plain; charset=utf-8" . "\r\n";
$headers .= "From: ".$from . "\r\n";

Return mail($to, $subject, $message, $headers);
}

function get_page_url(){

// Find out the URL of a PHP file

$url = "http".(empty($_SERVER["HTTPS"])?"":"s")."://".$_SERVER["SERVER_NAME"];

If(isset($_SERVER["REQUEST_URI"]) && $_SERVER["REQUEST_URI"] != ""){
$url.= $_SERVER["REQUEST_URI"];
}
else{
$url.= $_SERVER["PATH_INFO"];
}

Return $url;
}

function rate_limit($ip, $limit_hour = 20, $limit_10_min = 10){

// The number of login attempts for the last hour by this IP address

$count_hour = ORM::for_table("reg_login_attempt")
->
->where_raw("ts > SUBTIME(NOW(),"1:00")")
->count();

// The number of login attempts for the last 10 minutes by this IP address

$count_10_min = ORM::for_table("reg_login_attempt")
->where("ip", sprintf("%u", ip2long($ip)))
->where_raw("ts > SUBTIME(NOW(),"0:10")")
->count();

If($count_hour > $limit_hour || $count_10_min > $limit_10_min){
throw new Exception("Too many login attempts!");
}
}

function rate_limit_tick($ip, $email){

// Create a new record in the login attempt table

$login_attempt = ORM::for_table("reg_login_attempt")->create();

$login_attempt->email = $email;
$login_attempt->ip = sprintf("%u", ip2long($ip));

$login_attempt->save();
}

function redirect($url){
header("Location: $url");
exit;
}
Функции rate_limit и rate_limit_tick позволяют нам ограничивать число попыток авторизации на определенный промежуток времени. Попытки авторизации записываются в базу данных reg_login_attempt. Эти функции запускаются при проведении подтверждения формы авторизации, как можно видеть в следующем фрагменте кода.

Нижеприведенный код был взят из index.php, и он отвечает за подтверждение формы авторизации. Он возвращает JSON-ответ, который управляется кодом jQuery, который мы видели в assets/js/script.js.

index.php

If(!empty($_POST) && isset($_SERVER["HTTP_X_REQUESTED_WITH"])){

// Output a JSON header

Header("Content-type: application/json");

// Is the email address valid?

If(!isset($_POST["email"]) || !filter_var($_POST["email"], FILTER_VALIDATE_EMAIL)){
throw new Exception("Please enter a valid email.");
}

// This will throw an exception if the person is above
// the allowed login attempt limits (see functions.php for more):
rate_limit($_SERVER["REMOTE_ADDR"]);

// Record this login attempt
rate_limit_tick($_SERVER["REMOTE_ADDR"], $_POST["email"]);

// Send the message to the user

$message = "";
$email = $_POST["email"];
$subject = "Your Login Link";

If(!User::exists($email)){
$subject = "Thank You For Registering!";
$message = "Thank you for registering at our site!\n\n";
}

// Attempt to login or register the person
$user = User::loginOrRegister($_POST["email"]);

$message.= "You can login from this URL:\n";
$message.= get_page_url()."?tkn=".$user->generateToken()."\n\n";

$message.= "The link is going expire automatically after 10 minutes.";

$result = send_email($fromEmail, $_POST["email"], $subject, $message);

If(!$result){
throw new Exception("There was an error sending your email. Please try again.");
}

Die(json_encode(array(
"message" => "Thank you! We\"ve sent a link to your inbox. Check your spam folder as well."
)));
}
}
catch(Exception $e){

Die(json_encode(array(
"error"=>1,
"message" => $e->getMessage()
)));
}
При успешной авторизации или регистрации, вышеприведенный код отсылает email человеку с ссылкой для авторизации. Token (лексема) становится доступной в качестве $_GET-переменной "tkn" ввиду сгенерированного URL.

index.php

If(isset($_GET["tkn"])){

// Is this a valid login token?
$user = User::findByToken($_GET["tkn"]);

// Yes! Login the user and redirect to the protected page.

$user->login();
redirect("protected.php");
}

// Invalid token. Redirect back to the login form.
redirect("index.php");
}
Запуск $user->login() создаст необходимые переменные для сессии, что позволит пользователю оставаться авторизованным при последующих входах.

Выход из системы реализуется примерно таким же образом:

Index.php

If(isset($_GET["logout"])){

$user = new User();

If($user->loggedIn()){
$user->logout();
}

Redirect("index.php");
}
В конце кода мы снова перенаправляем пользователя на index.php, поэтому параметр?logout=1 в URL исключается.

Нашему файлу index.php также потребуется защита – мы не хотим, чтобы уже авторизованные пользователи видели форму. Для этого мы используем метод $user->loggedIn():

Index.php

$user = new User();

if($user->loggedIn()){
redirect("protected.php");
}
Наконец, давайте посмотрим, как можно защитить страницу вашего сайта, и сделать ее доступной только после авторизации:

protected.php

// To protect any php page on your site, include main.php
// and create a new User object. It"s that simple!

require_once "includes/main.php";

$user = new User();

if(!$user->loggedIn()){
redirect("index.php");
}
После этой проверки вы можете быть уверены в том, что пользователь успешно авторизовался. У вас также будет доступ к данным, которые хранятся в базе данных в качестве свойств объекта $user. Чтобы вывести email пользователя и их ранг, воспользуйтесь следующим кодом:

Echo "Your email: ".$user->email;
echo "Your rank: ".$user->rank();
Здесь rank() – это метод, так как колонка rank в базе данных обычно содержит числа (0 для обычных пользователей и 1 для администраторов), и нам нужно преобразовать это все в названия рангов, что реализуется при помощи данного метода. Чтобы преобразовать обычного пользователя в администратора, просто отредактируйте запись о пользователе в phpmyadmin (либо в любой другой программе по работе с базами данных). Будучи администратором, пользователь не будет наделен какими-то особыми возможностями. Вы сами в праве выбирать, каким правами наделять администраторов.

Готово!

На этом наша простенькая система регистрации готова! Вы можете использовать ее на уже существующем PHP-сайте, либо модернизировать ее, придерживаясь собственных требований.

Сегoдня мы рассмотрим эксплуатацию критической 1day-уязвимости в популярной CMS Joomla, которая прогремела на просторах интернета в конце октября. Речь пойдет об уязвимостях с номерами CVE-2016-8869 , CVE-2016-8870 и CVE-2016-9081 . Все три происходят из одного кусочка кода, который пять долгих лет томился в недрах фреймворка в ожидании своего часа, чтобы затем вырваться на свободу и принести с собой хаос, взломанные сайты и слезы ни в чем не повинных пользователей этой Joomla. Лишь самые доблестные и смелые разработчики, чьи глаза красны от света мониторов, а клавиатуры завалены хлебными крошками, смогли бросить вызов разбушевавшейся нечисти и возложить ее голову на алтарь фиксов.

WARNING

Вся информация предоставлена исключительно в ознакомительных целях. Ни редакция, ни автор не несут ответственности за любой возможный вред, причиненный материалами данной статьи.

С чего все началось

6 октября 2016 года Дэмис Пальма (Demis Palma) создал топик на Stack Exchange , в котором поинтересовался: а почему, собственно, в Joomla версии 3.6 существуют два метода регистрации пользователей с одинаковым названием register() ? Первый находится в контроллере UsersControllerRegistration , а второй - в UsersControllerUser . Дэмис хотел узнать, используется ли где-то метод UsersControllerUser::register() , или это лишь эволюционный анахронизм, оставшийся от старой логики. Его беспокоил тот факт, что, даже если этот метод не используется никаким представлением, он может быть вызван при помощи сформированного запроса. На что получил ответ от девелопера под ником itoctopus, подтвердившего: проблема действительно существует. И направил отчет разработчикам Joomla.

Далее события развивались самым стремительным образом. 18 октября разработчики Joomla принимают репорт Дэмиса, который к тому времени набросал PoC, позволяющий регистрировать пользователя. Он опубликовал заметку на своем сайте , где в общих чертах рассказал о найденной проблеме и мыслях по этому поводу. В этот же день выходит новая версия Joomla 3.6.3, которая все еще содержит уязвимый код.

После этого Давиде Тампеллини (Davide Tampellini) раскручивает баг до состояния регистрации не простого пользователя, а администратора. И уже 21 октября команде безопасности Joomla прилетает новый кейс. В нем речь уже идет о повышении привилегий . В этот же день на сайте Joomla появляется анонс о том, что во вторник, 25 октября, будет выпущена очередная версия с порядковым номером 3.6.3, которая исправляет критическую уязвимость в ядре системы.

25 октября Joomla Security Strike Team находит последнюю проблему, которую создает обнаруженный Дэмисом кусок кода. Затем в главную ветку официального репозитория Joomla пушится коммит от 21 октября с неприметным названием Prepare 3.6.4 Stable Release , который фиксит злосчастный баг.

После этого камин-аута к междусобойчику разработчиков подключаются многочисленные заинтересованные личности - начинают раскручивать уязвимость и готовить сплоиты.

27 октября исследователь Гарри Робертс (Harry Roberts) выкладывает в репозиторий Xiphos Research готовый эксплоит , который может загружать PHP-файл на сервер с уязвимой CMS.

Детали

Что ж, с предысторией покончено, переходим к самому интересному - разбору уязвимости. В качестве подопытной версии я установил Joomla 3.6.3, поэтому все номера строк будут актуальны именно для этой версии. А все пути до файлов, которые ты увидишь далее, будут указываться относительно корня установленной CMS.

Благодаря находке Дэмиса Пальмы мы знаем, что есть два метода, которые выполняют регистрацию пользователя в системе. Первый используется CMS и находится в файле /components/com_users/controllers/registration.php:108 . Второй (тот, что нам и нужно будет вызвать), обитает в /components/com_users/controllers/user.php:293 . Посмотрим на него поближе.

286: /** 287: * Method to register a user. 288: * 289: * @return boolean 290: * 291: * @since 1.6 292: */ 293: public function register() 294: { 295: JSession::checkToken("post") or jexit(JText::_("JINVALID_TOKEN")); ... 300: // Get the form data. 301: $data = $this->input->post->get("user", array(), "array"); ... 315: $return = $model->validate($form, $data); 316: 317: // Check for errors. 318: if ($return === false) 319: { ... 345: // Finish the registration. 346: $return = $model->register($data);

Здесь я оставил только интересные строки. Полную версию уязвимого метода можно посмотреть в репозитории Joomla.

Разберемся, что происходит при обычной регистрации пользователя: какие данные отправляются и как они обрабатываются. Если регистрация пользователей включена в настройках, то форму можно найти по адресу http://joomla.local/index.php/component/users/?view=registration .


Легитимный запрос на регистрацию пользователя выглядит как на следующем скриншоте.


За работу с пользователями отвечает компонент com_users . Обрати внимание на параметр task в запросе. Он имеет формат $controller.$method . Посмотрим на структуру файлов.

Имена скриптов в папке controllers соответствуют названиям вызываемых контроллеров. Так как в нашем запросе сейчас $controller = "registration" , то вызовется файл registration.php и его метод register() .

Внимание, вопрос: как передать обработку регистрации в уязвимое место в коде? Ты наверняка уже догадался. Имена уязвимого и настоящего методов совпадают (register), поэтому нам достаточно поменять название вызываемого контроллера. А где у нас находится уязвимый контроллер? Правильно, в файле user.php . Получается $controller = "user" . Собираем все вместе и получаем task = user.register . Теперь запрос на регистрацию обрабатывается нужным нам методом.


Второе, что нам нужно сделать, - это отправить данные в правильном формате. Тут все просто. Легитимный register() ждет от нас массив под названием jform , в котором мы передаем данные для регистрации - имя, логин, пароль, почту (см. скриншот с запросом).

  • /components/com_users/controllers/registration.php: 124: // Get the user data. 125: $requestData = $this->input->post->get("jform", array(), "array");

Наш подопечный получает эти данные из массива с именем user .

  • /components/com_users/controllers/user.php: 301: // Get the form data. 302: $data = $this->input->post->get("user", array(), "array");

Поэтому меняем в запросе имена всех параметров с jfrom на user .

Третий наш шаг - это нахождение валидного токена CSRF, так как без него никакой регистрации не будет.

  • /components/com_users/controllers/user.php: 296: JSession::checkToken("post") or jexit(JText::_("JINVALID_TOKEN"));

Он выглядит как хеш MD5, а взять его можно, например, из формы авторизации на сайте /index.php/component/users/?view=login .


Теперь можно создавать пользователей через нужный метод. Если все получилось, то поздравляю - ты только что проэксплуатировал уязвимость CVE-2016-8870 «отсутствующая проверка разрешений на регистрацию новых пользователей».

Вот как она выглядит в «рабочем» методе register() из контроллера UsersControllerRegistration:

  • /components/com_users/controllers/registration.php: 113: // If registration is disabled - Redirect to login page. 114: if (JComponentHelper::getParams("com_users")->get("allowUserRegistration") == 0) 115: { 116: $this->setRedirect(JRoute::_("index.php?option=com_users&view=login", false)); 117: 118: return false; 119: }

А так в уязвимом:

  • /components/com_users/controllers/user.php:

Ага, никак.

Чтобы понять вторую, гораздо более серьезную проблему, отправим сформированный нами запрос и проследим, как он выполняется на различных участках кода. Вот кусок, который отвечает за проверку отправленных пользователем данных в рабочем методе:

Продолжение доступно только участникам

Вариант 1. Присоединись к сообществу «сайт», чтобы читать все материалы на сайте

Членство в сообществе в течение указанного срока откроет тебе доступ ко ВСЕМ материалам «Хакера», увеличит личную накопительную скидку и позволит накапливать профессиональный рейтинг Xakep Score!

Creating a membership based site seems like a daunting task at first. If you ever wanted to do this by yourself, then just gave up when you started to think how you are going to put it together using your PHP skills, then this article is for you. We are going to walk you through every aspect of creating a membership based site, with a secure members area protected by password.

The whole process consists of two big parts: user registration and user authentication. In the first part, we are going to cover creation of the registration form and storing the data in a MySQL database. In the second part, we will create the login form and use it to allow users access in the secure area.

Download the code

You can download the whole source code for the registration/login system from the link below:

Configuration & Upload
The ReadMe file contains detailed instructions.

Open the source\include\membersite_config.php file in a text editor and update the configuration. (Database login, your website’s name, your email address etc).

Upload the whole directory contents. Test the register.php by submitting the form.

The registration form

In order to create a user account, we need to gather a minimal amount of information from the user. We need his name, his email address and his desired username and password. Of course, we can ask for more information at this point, but a long form is always a turn-off. So let’s limit ourselves to just those fields.

Here is the registration form:

Register

So, we have text fields for name, email and the password. Note that we are using the for better usability.

Form validation

At this point it is a good idea to put some form validation code in place, so we make sure that we have all the data required to create the user account. We need to check if name and email, and password are filled in and that the email is in the proper format.

Handling the form submission

Now we have to handle the form data that is submitted.

Here is the sequence (see the file fg_membersite.php in the downloaded source):

function RegisterUser() { if(!isset($_POST["submitted"])) { return false; } $formvars = array(); if(!$this->ValidateRegistrationSubmission()) { return false; } $this->CollectRegistrationSubmission($formvars); if(!$this->SaveToDatabase($formvars)) { return false; } if(!$this->SendUserConfirmationEmail($formvars)) { return false; } $this->SendAdminIntimationEmail($formvars); return true; }

First, we validate the form submission. Then we collect and ‘sanitize’ the form submission data (always do this before sending email, saving to database etc). The form submission is then saved to the database table. We send an email to the user requesting confirmation. Then we intimate the admin that a user has registered.

Saving the data in the database

Now that we gathered all the data, we need to store it into the database.
Here is how we save the form submission to the database.

function SaveToDatabase(&$formvars) { if(!$this->DBLogin()) { $this->HandleError("Database login failed!"); return false; } if(!$this->Ensuretable()) { return false; } if(!$this->IsFieldUnique($formvars,"email")) { $this->HandleError("This email is already registered"); return false; } if(!$this->IsFieldUnique($formvars,"username")) { $this->HandleError("This UserName is already used. Please try another username"); return false; } if(!$this->InsertIntoDB($formvars)) { $this->HandleError("Inserting to Database failed!"); return false; } return true; }

Note that you have configured the Database login details in the membersite_config.php file. Most of the cases, you can use “localhost” for database host.
After logging in, we make sure that the table is existing.(If not, the script will create the required table).
Then we make sure that the username and email are unique. If it is not unique, we return error back to the user.

The database table structure

This is the table structure. The CreateTable() function in the fg_membersite.php file creates the table. Here is the code:

function CreateTable() { $qry = "Create Table $this->tablename (". "id_user INT NOT NULL AUTO_INCREMENT ,". "name VARCHAR(128) NOT NULL ,". "email VARCHAR(64) NOT NULL ,". "phone_number VARCHAR(16) NOT NULL ,". "username VARCHAR(16) NOT NULL ,". "password VARCHAR(32) NOT NULL ,". "confirmcode VARCHAR(32) ,". "PRIMARY KEY (id_user)". ")"; if(!mysql_query($qry,$this->connection)) { $this->HandleDBError("Error creating the table \nquery was\n $qry"); return false; } return true; }

The id_user field will contain the unique id of the user, and is also the primary key of the table. Notice that we allow 32 characters for the password field. We do this because, as an added security measure, we will store the password in the database encrypted using MD5. Please note that because MD5 is an one-way encryption method, we won’t be able to recover the password in case the user forgets it.

Inserting the registration to the table

Here is the code that we use to insert data into the database. We will have all our data available in the $formvars array.

function InsertIntoDB(&$formvars) { $confirmcode = $this->MakeConfirmationMd5($formvars["email"]); $insert_query = "insert into ".$this->tablename."(name, email, username, password, confirmcode) values ("" . $this->SanitizeForSQL($formvars["name"]) . "", "" . $this->SanitizeForSQL($formvars["email"]) . "", "" . $this->SanitizeForSQL($formvars["username"]) . "", "" . md5($formvars["password"]) . "", "" . $confirmcode . "")"; if(!mysql_query($insert_query ,$this->connection)) { $this->HandleDBError("Error inserting data to the table\nquery:$insert_query"); return false; } return true; }

Notice that we use PHP function md5() to encrypt the password before inserting it into the database.
Also, we make the unique confirmation code from the user’s email address.

Sending emails

Now that we have the registration in our database, we will send a confirmation email to the user. The user has to click a link in the confirmation email to complete the registration process.

function SendUserConfirmationEmail(&$formvars) { $mailer = new PHPMailer(); $mailer->CharSet = "utf-8"; $mailer->AddAddress($formvars["email"],$formvars["name"]); $mailer->Subject = "Your registration with ".$this->sitename; $mailer->From = $this->GetFromAddress(); $confirmcode = urlencode($this->MakeConfirmationMd5($formvars["email"])); $confirm_url = $this->GetAbsoluteURLFolder()."/confirmreg.php?code=".$confirmcode; $mailer->Body ="Hello ".$formvars["name"]."\r\n\r\n". "Thanks for your registration with ".$this->sitename."\r\n". "Please click the link below to confirm your registration.\r\n". "$confirm_url\r\n". "\r\n". "Regards,\r\n". "Webmaster\r\n". $this->sitename; if(!$mailer->Send()) { $this->HandleError("Failed sending registration confirmation email."); return false; } return true; }

Updates

9th Jan 2012
Reset Password/Change Password features are added
The code is now shared at GitHub .

Welcome back UserFullName(); ?>!

License


The code is shared under LGPL license. You can freely use it on commercial or non-commercial websites.

No related posts.

Comments on this entry are closed.

In this tutorial, I walk you through the complete process of creating a user registration system where users can create an account by providing username, email and password, login and logout using PHP and MySQL. I will also show you how you can make some pages accessible only to logged in users. Any other user not logged in will not be able to access the page.

If you prefer a video, you can watch it on my YouTube channel

The first thing we"ll need to do is set up our database.

Create a database called registration . In the registration database, add a table called users . The users table will take the following four fields.

  • username - varchar(100)
  • email - varchar(100)
  • password - varchar(100)

You can create this using a MySQL client like PHPMyAdmin.

Or you can create it on the MySQL prompt using the following SQL script:

CREATE TABLE `users` (`id` int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY, `username` varchar(100) NOT NULL, `email` varchar(100) NOT NULL, `password` varchar(100) NOT NULL) ENGINE=InnoDB DEFAULT CHARSET=latin1;

And that"s it with the database.

Now create a folder called registration in a directory accessible to our server. i.e create the folder inside htdocs (if you are using XAMPP server) or inside www (if you are using wampp server).

Inside the folder registration, create the following files:

Open these files up in a text editor of your choice. Mine is Sublime Text 3.

Registering a user

Open the register.php file and paste the following code in it:

regiser.php:

Register

Already a member? Sign in

Nothing complicated so far right?

A few things to note here:

First is that our form"s action attribute is set to register.php. This means that when the form submit button is clicked, all the data in the form will be submitted to the same page (register.php). The part of the code that receives this form data is written in the server.php file and that"s why we are including it at the very top of the register.php file.

Notice also that we are including the errors.php file to display form errors. We will come to that soon.

As you can see in the head section, we are linking to a style.css file. Open up the style.css file and paste the following CSS in it:

* { margin: 0px; padding: 0px; } body { font-size: 120%; background: #F8F8FF; } .header { width: 30%; margin: 50px auto 0px; color: white; background: #5F9EA0; text-align: center; border: 1px solid #B0C4DE; border-bottom: none; border-radius: 10px 10px 0px 0px; padding: 20px; } form, .content { width: 30%; margin: 0px auto; padding: 20px; border: 1px solid #B0C4DE; background: white; border-radius: 0px 0px 10px 10px; } .input-group { margin: 10px 0px 10px 0px; } .input-group label { display: block; text-align: left; margin: 3px; } .input-group input { height: 30px; width: 93%; padding: 5px 10px; font-size: 16px; border-radius: 5px; border: 1px solid gray; } .btn { padding: 10px; font-size: 15px; color: white; background: #5F9EA0; border: none; border-radius: 5px; } .error { width: 92%; margin: 0px auto; padding: 10px; border: 1px solid #a94442; color: #a94442; background: #f2dede; border-radius: 5px; text-align: left; } .success { color: #3c763d; background: #dff0d8; border: 1px solid #3c763d; margin-bottom: 20px; }

Now the form looks beautiful.

Let"s now write the code that will receive information submitted from the form and store (register) the information in the database. As promised earlier, we do this in the server.php file.

Open server.php and paste this code in it:

server.php

Sessions are used to track logged in users and so we include a session_start() at the top of the file.

The comments in the code pretty much explain everything, but I"ll highlight a few things here.

The if statement determines if the reg_user button on the registration form is clicked. Remember, in our form, the submit button has a name attribute set to reg_user and that is what we are referencing in the if statement.

All the data is received from the form and checked to make sure that the user correctly filled the form. Passwords are also compared to make sure they match.

If no errors were encountered, the user is registered in the users table in the database with a hashed password. The hashed password is for security reasons. It ensures that even if a hacker manages to gain access to your database, they would not be able to read your password.

But error messages are not displaying now because our errors.php file is still empty. To display the errors, paste this code in the errors.php file.

0) : ?>

When a user is registered in the database, they are immediately logged in and redirected to the index.php page.

And that"s it for registration. Let"s look at user login.

Login user

Logging a user in is an even easier thing to do. Just open the login page and put this code inside it:

Registration system PHP and MySQL

Login

Not yet a member? Sign up

Everything on this page is quite similar to the register.php page.

Now the code that logs the user in is to be written in the same server.php file. So open the server.php file and add this code at the end of the file:

// ... // LOGIN USER if (isset($_POST["login_user"])) { $username = mysqli_real_escape_string($db, $_POST["username"]); $password = mysqli_real_escape_string($db, $_POST["password"]); if (empty($username)) { array_push($errors, "Username is required"); } if (empty($password)) { array_push($errors, "Password is required"); } if (count($errors) == 0) { $password = md5($password); $query = "SELECT * FROM users WHERE username="$username" AND password="$password""; $results = mysqli_query($db, $query); if (mysqli_num_rows($results) == 1) { $_SESSION["username"] = $username; $_SESSION["success"] = "You are now logged in"; header("location: index.php"); }else { array_push($errors, "Wrong username/password combination"); } } } ?>

Again all this does is check if the user has filled the form correctly, verifies that their credentials match a record from the database and logs them in if it does. After logging in, the user is redirected them to the index.php file with a success message.

Now let"s see what happens in the index.php file. Open it up and paste the following code in it:

Home

Home Page

Welcome

logout

The first if statement checks if the user is already logged in. If they are not logged in, they will be redirected to the login page. Hence this page is accessible to only logged in users. If you"d like to make any page accessible only to logged in users, all you have to do is place this if statement at the top of the file.

The second if statement checks if the user has clicked the logout button. If yes, the system logs them out and redirects them back to the login page.

Now go on, customize it to suit your needs and build an awesome site. If you have any worries or anything you need to clarify, leave it in the comments below and help will come.

You can always support by sharing on social media or recommending my blog to your friends and colleagues.


Close