Адоніс register form php. Створення простої системи реєстрації користувачів на PHP і MySQL

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.

Learn how to create a complete blog with PHP and MySQL database with my free course on YouTube.

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: # 3c7 63d; 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.

Доброго времени суток друзі! Давай з Вами розглянемо реєстрацію користувачів на PHP. Для початку давайте визначимо умови для нашої реєстрації користувачів:

  • Пароль шифруємо за допомогою алгоритму MD5
  • Пароль будемо "солити"
  • Перевірка на зайнятість Логіна
  • Активація користувача листом.
  • Запис і зберігання даних в СУБД MySQL

Для написання даного скрипта нам потрібно зрозуміти, що таке реєстрація користувача. Реєстрація користувача - це отримання даних реального користувача, обробка та зберігання даних.

Якщо пояснювати простими словами то реєстрація це всього лише запис і зберігання певних даних за якими ми можемо авторизувати користувача в нашому випадку - це Логін і Пароль.

Авторизація - надання певній особі або групі осіб прав на виконання певних дій, а також процес перевірки даних прав при спробі виконання цих дій. Проше кажучи за допомогою авторизації ми можемо розмежувати доступ до того чи іншого контенту на нашому сайті.

Розглянемо структуру каталогів скриптів для реалізації нашої реєстрації з авторизацією. Нам потрібно розбити скрипти на логічні складові. Модулі реєстрації та авторизації ми помістивши в окремий каталог. Так само в окремі каталоги ми помістимо підключення до бази даних MySQL, Файл з одними функціями, файл стилів CSSі наш шаблон HTML. Дана структура дозволяє швидко орієнтуватися в скриптах. Уявіть собі, що у Вас великий сайт з купою модулями і т.д. і якщо не буде порядку, то буде дуже складно щось відшукати в такому бардаку.

Так як ми будемо зберігати всі дані в СУБД MySQL, То давайте створимо не більшу таблицю в якій будемо зберігати дані про реєстрацію.

Для початку потрібно створити таблицю в базі даних. таблицю назвемо bez_regде bez- це префікс таблиці, а regназва таблиці.

Структура таблиці: bez_reg

- - Структура таблиці `bez_reg` - CREATE TABLE IF NOT EXISTS` bez_reg` ( `id` int (11) NOT NULL AUTO_INCREMENT,` login` varchar (200) NOT NULL, `pass` varchar (32) NOT NULL , `salt` varchar (32) NOT NULL,` active_hex` varchar (32) NOT NULL, `status` int (1) NOT NULL, PRIMARY KEY (` id`)) ENGINE = MyISAM DEFAULT CHARSET = utf8 AUTO_INCREMENT = 1;

Тепер створимо основні скрипти для подальшої роботи.

файл INDEX.PHP

файл CONFIG.PHP

"); ?>

файл 404.HTML

Помилка 404

Помилка 404

На сторінці сталася помилка 404

повернутися

файл BD.PHP

файл INDEX.HTML

Реєстрація користувачів PHP MySQL з активацією листом

файл FUNCT.PHP

"." \ N "; if (is_array ($ data)) (foreach ($ data as $ val) $ err. ="

  • ". $ Val."
  • "." \ N ";) else $ err. ="
  • ". $ Data."
  • "." \ N "; $ err. =""." \ N "; return $ err;) / ** Проста обгортка для запитів до MySQL * @param string $ sql * / function mysqlQuery ($ sql) ($ res = mysql_query ($ sql); / * Перевіряємо результат Це показує реальний запит, надісланий до MySQL, а також помилку. Зручно при налагодженні. * / if (! $ res) ($ message = "Невірний запит:". mysql_error (). "\ n"; $ message. = "запит цілком : ". $ sql; die ($ message);) return $ res;) / ** Простий генератор солі * @param string $ sql * / function salt () ($ salt = substr (md5 (uniqid ()), - 8); return $ salt;)

    Давайте приступимо до написання реєстрації. Для початку нам потрібно буде зробити шаблон форми реєстрації, щоб користувач зміг внести свої дані для обробки. Далі нам потрібно буде написати сам обробник форми, який перевірить на коректність введені дані користувача. Після того як дані успішно перевірені записуємо їх в нашу базу даних і відправляємо лист користувачеві для активації його облікового запису.

    файл REG.PHP

    Ви успішно зареєструвалися! Будь ласка активуйте свій аккаунт !!"; // Виробляємо активацію облікового запису if (isset ($ _ GET [" key "])) (// Перевіряємо ключ $ sql =" SELECT * FROM `". BEZ_DBPREFIX. "Reg` WHERE` active_hex` = "". Escape_str ( $ _GET [ "key"]). "" "; $ res = mysqlQuery ($ sql); if (mysql_num_rows ($ res) == 0) $ err =" Ключ активації не вірний! "; // Перевіряємо наявність помилок і виводимо користувачеві if (count ($ err)> 0) echo showErrorMessage ($ err); else (// Отримуємо адреса користувача $ row = mysql_fetch_assoc ($ res); $ email = $ row [ "login"]; // Активуємо аккаунт користувача $ sql = "UPDATE` ". BEZ_DBPREFIX." reg` SET `status` = 1 WHERE` login` = "". $ email. "" "; $ res = mysqlQuery ($ sql); // Відправляємо лист для активації $ title = "(! LANG: Ваш аккаунт на http: // сайт успішно активований"; $message = "Поздравляю Вас, Ваш аккаунт на http://сайт успешно активирован"; sendMessageMail($email, BEZ_MAIL_AUTOR, $title, $message); /*Перенаправляем пользователя на нужную нам страницу*/ header("Location:". BEZ_HOST ."less/reg/?mode=reg&active=ok"); exit; } } /*Если нажата кнопка на регистрацию, начинаем проверку*/ if(isset($_POST["submit"])) { //Утюжим пришедшие данные if(empty($_POST["email"])) $err = "Поле Email не может быть пустым!"; else { if(!preg_match("/^!} [Email protected](+ \.) + (2,6) $ / i ", $ _POST [" email "])) $ err =" Неможливо правильно введений E-mail "." \ N ";) if (empty ($ _ POST [ "pass"])) $ err = "Поле Пароль не може бути порожнім"; if (empty ($ _ POST [ "pass2"])) $ err = "Поле Підтвердження пароля не може бути порожнім"; // Перевіряємо наявність помилок і виводимо користувачеві if (count ($ err)> 0) echo showErrorMessage ($ err); else (/ * Продовжуємо перевіряти введені дані Перевіряємо на совподеніе паролі * / if ($ _ POST [ "pass"]! = $ _POST [ "pass2" ]) $ err = "Паролі не совподает"; // Перевіряємо наявність помилок і виводимо користувачеві if (count ($ err)> 0) echo showErrorMessage ($ err); else (/ * Перевіряємо чи існує у нас такий користувач в БД * / $ sql = "SELECT` login` FROM `". BEZ_DBPREFIX. "reg` WHERE` login` = "". escape_str ($ _ POST [ "email"]). "" "; $ res = mysqlQuery ($ sql); if (mysql_num_rows ($ res)> 0) $ err = "На жаль Логін: ". $ _POST [" email "]."зайнятий! "; // Перевіряємо наявність помилок і виводимо користувачеві if (count ($ err)> 0) echo showErrorMessage ($ err); else (// Отримуємо хеш солі $ salt = salt (); // Солимо пароль $ pass = md5 (md5 ($ _ POST [ "pass"]). $ salt); / * Якщо все добре, пишемо дані в базу * / $ sql = "INSERT INTO` ". BEZ_DBPREFIX." reg` VALUES ( "", "" . escape_str ($ _ POST [ "email"]). "", "". $ pass. "", "". $ salt. "", "". md5 ($ salt). "", 0) "; $ res = mysqlQuery ($ sql); // Відправляємо лист для активації $ url = BEZ_HOST. "less / reg /? mode = reg & key =". md5 ($ salt); $ title = "(! LANG: Реєстрація на http: / / сайт"; $message = "Для активации Вашего акаунта пройдите по ссылке ". $url .""; sendMessageMail($_POST["email"], BEZ_MAIL_AUTOR, $title, $message); //Сбрасываем параметры header("Location:". BEZ_HOST ."less/reg/?mode=reg&status=ok"); exit; } } } } ?>!}

    файл REG_FORM.HTML

    Реєстрація користувачів PHP MySQL з активацією листом

    E-mail *:
    пароль *:
    підтвердження пароля *:

    Поля зі значком *обов'язкові для заповнення

    Так як реєстрація користувачів у нас готова, саме час написати авторизацію. Створимо форму для авторизації користувачів, далі напишемо обробник форми авторизації і на останок зробимо скрипт show.phpякий буде показувати нам авторизовані ми в системі чи ні.

    файл AUTH.PHP

    0) echo showErrorMessage ($ err); else (/ * Створюємо запит на вибірку з бази даних для перевірки достовірності користувача * / $ sql = "SELECT * FROM` ". BEZ_DBPREFIX." reg` WHERE `login` =" ". escape_str ($ _ POST [" email "]) . "" AND `status` = 1"; $ res = mysqlQuery ($ sql); // Якщо логін совподает, перевіряємо пароль if (mysql_num_rows ($ res)> 0) (// Отримуємо дані з таблиці $ row = mysql_fetch_assoc ( $ res); if (md5 (md5 ($ _ POST [ "pass"]). $ row [ "salt"]) == $ row [ "pass"]) ($ _SESSION [ "user"] = true; // скидаємо параметри header ( "Location:". BEZ_HOST. "less / reg /? mode = auth"); exit;) else echo showErrorMessage ( "Неправильний пароль!");) else echo showErrorMessage ( "Логін ". $ _POST [" email "]."не знайден! ");))?>

    Для тих у кого остання версія PHP викладаю даний скрипт з використанням PDOтому розширення MySQLзастаріло і було видалено з нової версії PHP. Завантажити реєстрація і авторизація php mysql pdo

    Архів оновлено 24.02.2015г.

    Увага:Якщо ви використовуєте цей скрипт на локальному сервері типу DENWER,XAMPP, То не варто чекати листів на свою поштову скриньку. Листи лежать в заглушці sendmail. В Denwerви їх можете знайти по шляху Z: \ tmp \! Sendmail \відкрити ці файли ви зможете в будь-якому поштовому клієнті.

    Для того, щоб розділити відвідувачів сайту на деякі групи на сайті обов'язково встановлюють невелику систему реєстрації на php. Таким чином ви умовно поділяєте відвідувачів на дві групи просто випадкових відвідувачів і на більш привілейовану групу користувачів, яким ви видаєте більш цінну інформацію.

    У більшості випадків, застосовують більш спрощену систему реєстрації, яка написана на php в одному файлі register.php.

    Отже, ми трохи відволіклися, а зараз розглянемо більш докладно файл реєстрації.

    файл register.php

    Для того, щоб у вас це не відняло безліч часу створимо систему, яка буде збирати користувачів, приймаючи від них мінімальну контактну інформацію. В даному випадку все будемо заносити в базу даних mysql. Для максимальної швидкості роботи бази, будемо створювати таблицю users в форматі MyISAM і в кодуванні utf-8.

    Зверніть увагу! Писати все скрипти потрібно завжди в одному кодуванні. Всі файли сайту і база даних MySql повинні бути в єдиній кодуванні. Найпоширеніші кодування UTF-8 і Windows-1251.

    Для чого потрібно писати все в одному кодуванні ми поговоримо як-небудь пізніше. А поки прийміть цю інформацію як найсуворіше правило створення скриптів інакше в майбутньому виникнуть проблеми з роботою скриптів. Нічого страшного, звичайно, але просто втратите багато часу для пошуку помилок в роботі скрипта.

    Як буде працювати сам скрипт?

    Ми хочемо все спростити і отримати швидкий результат. Тому будемо отримувати від користувачів тільки логін, email і його пароль. А для захисту від спам-роботів, встановимо невелику капчу. Інакше який-небудь хлопчик з Лондона напише невеликий робот-парсер, який заповнить всю базу липовими користувачами за кілька хвилин, і буде радіти своїй геніальності і безкарності.

    Ось сам скрипт. Все записано в одному файлі register.php:

    ! `; // червоний знак питання $ sha = $ sh. "Scripts / pro /"; // шлях до основної папці $ bg = `bgcolor =" # E1FFEB "`; // фоновий колір рядків?> Приклад скрипта реєстрації register.php style.css "/>

    В даному випадку скрипт звертається до самого себе. І є формою і обробником даних занесених в форму. Звертаю вашу увагу, що файл стиснутий zip-архівом і містить файл конфігурації config.php, дамп бази даних users, файл містить допоміжні функції functions.php, файл стилів style.css і сам файл register.php. Також кілька файлів, які відповідають за роботу і генерацію символів капчи.

    Процес створення системи реєстрації - це досить великий обсяг роботи. Вам потрібно написати код, який би перевіряв валідність 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-сайті, або модернізувати її, дотримуючись власних вимог.

    PHP | 25 Jan 2017 | Clever Techie

    In this lesson, we learn how to create user account registration form with PHP validation rules, upload profile avatar image and insert user data in MySQL database. We will then retrieve the information from the database and display it on the user profile welcome page. Here is what the welcome page is going to look like:

    Setting up Form CSS and HTML

    First, go ahead and copy the HTML source from below codepen and place the code in a file called form.php. Also create another file named form.css in the same directory and copy and paste all of the CSS code from the codepen below into it:

    Once you "ve saved form.php and form.css, you may go ahead and run form.php to see what the form looks like. It should look exactly the same as the one showing in the" Result "tab from the codepen above .

    Creating the Database and Table

    Before we start adding PHP code to our form, let "s go ahead and create the database with a table which will store our registered users information in it. Below in the SQL script to create the database" accounts "and table" users ":

    CREATE DATABASE accounts; CREATE TABLE `accounts`.`users` (` id` INT NOT NULL AUTO_INCREMENT, `username` VARCHAR (100) NOT NULL,` email` VARCHAR (100) NOT NULL, `password` VARCHAR (100) NOT NULL,` avatar `VARCHAR (100) NOT NULL, PRIMARY KEY (` id`));

    Below is a complete code with error checking for connecting to MySQL database and running above SQL statements to create the database and users table:

    // connection variables $ host = "localhost"; $ User = "root"; $ Password = "mypass123"; // create mysql connection $ mysqli = new mysqli ($ host, $ user, $ password); if ($ mysqli-> connect_errno) (printf ( "Connection failed:% s \ n", $ mysqli-> connect_error); die ();) // create the database if (! $ mysqli-> query ( "CREATE DATABASE accounts2 ")) (printf (" Errormessage:% s \ n ", $ mysqli-> error);) // create users table with all the fields $ mysqli-> query (" CREATE TABLE `accounts2`.`users` ( `id` INT NOT NULL AUTO_INCREMENT,` username` VARCHAR (100) NOT NULL, `email` VARCHAR (100) NOT NULL,` password` VARCHAR (100) NOT NULL, `avatar` VARCHAR (100) NOT NULL, PRIMARY KEY ( `id`));") or die ($ mysqli-> error);

    With our HTML, CSS and the database table in place, we "re now reading to start working on our form. The first step is to create a place for error messages to show up and then we" ll start writing some form validation.

    Starting New Session for Error Messages

    Open up the form.php and add the following lines to it at the very top, make sure to use the php opening and closing tags (I have not included the html part of form.php to keep things clean).

    We have created new session because we "re going to need to access $ _SESSION [" message "] on the" welcome.php "page after user successfully registers. MySQL connection has also been created right away, so we can work with the database later on.

    We also need to print out $ _SESSION [ "message"] on the current page. From the beginning the message is set to "" (empty string) which is what we want, so nothing will be printed at this point. Let "s go ahead and add the message inside the proper DIV tag:

    Creating Validation Rules

    This form already comes with some validation rules, the keyword "required" inside the HTML input tags, is checking to make sure the field is not empty, so we don "t have to worry about empty fields. Also, by setting input type to "email and" password ", HTML5 validates the form for proper email and password formatting, so we don" t need to create any rules for those fields either.

    However, we still need to write some validation rules, to make sure the passwords are matching, the avatar file is in fact an image and make sure the user has been added to our database.

    Let "s create another file and call it validate.php to keep things well organized. We" ll also include this file from our form.php.

    The first thing we "re going to do inside validate.php is to make sure the form is being submitted.

    / * Validate.php * / // the form has been submitted with post method if ($ _SERVER [ "REQUEST_METHOD"] == "POST") ()

    Then we "ll check if the password and confirm password are equal to each other

    if ($ _SERVER [ "REQUEST_METHOD"] == "POST") (// check if two passwords are equal to each other if ($ _POST [ "password"] == $ _POST [ "confirmpassword"]) ())

    Working with Super Global Variables

    Note how we used super global variables $ _SERVER and $ _POST to get the information we needed. The keys names inside the $ _POST variable is available because we used method = "post" to submit our form.

    The key names are all the named HTML input fields with attribute name (eg: name = "password", name = "confirmpassword"):

    />

    To clarify a bit more, here is what the $ _POST would look like (assuming all the fields in the form have been filled out) if we used a print_r ($ _ POST) function on it, followed by die (); to terminate the script right after printing it. This is a good way of debugging your script and seeing what "s going on:

    if ($ _SERVER [ "REQUEST_METHOD"] == "POST") (print_r ($ _ POST); die (); / * output: Array (=> clevertechie => [Email protected]=> Mypass123 => mypass123 => Register) * /

    Now we "re going to get the rest of our submitted values ​​from $ _POST and get them properly formatted so they can be inserted to our MySQL database table

    // the form has been submitted with post if ($ _SERVER [ "REQUEST_METHOD"] == "POST") (if ($ _POST [ "password"] == $ _POST [ "confirmpassword"]) (// define other variables with submitted values ​​from $ _POST $ username = $ mysqli-> real_escape_string ($ _ POST [ "username"]); $ email = $ mysqli-> real_escape_string ($ _ POST [ "email"]); // md5 hash password for security $ password = md5 ($ _ POST [ "password"]); // path were our avatar image will be stored $ avatar_path = $ mysqli-> real_escape_string ( "images /".$_ FILES [" avatar "] [" name "]) ;))

    In the above code, we used real_escape_string () method to make sure our username, email and avatar_path are formatted properly to be inserted as a valid SQL string into the database. We also used md5 () hash function to create a hash string out of password for security.

    How File Uploading Works

    Also, notice the new super global variable $ _FILES, which holds the information about our image, which is the avatar being uploaded from the user "s computer. The $ _FILES variable is available because we used enctype =" multipart / form-data " in our form:

    Here is the output if we use the print_r ($ _ FILES) followed by die (); just like we did for the $ _POST variable:

    if ($ _SERVER [ "REQUEST_METHOD"] == "POST") (print_r ($ _ FILES); die (); / * output: Array (=> Array (=> guldan.png => image / png => C: \ Windows \ Temp \ php18D8.tmp => 0 => 98823)) * / // this is how we "re able to access the image name: $ _FILES [" avatar "] [" name "]; // guldan. png

    When the file is first uploaded, using the post method, it will be stored in a temporary directory. That directory can be accessed with $ _FILES [ "avatar"] [ "tmp_name"] which is "C: \ Windows \ Temp \ php18D8.tmp" from the output above.

    We can then copy that file from the temporary directory, to the directory that we want which is $ avatar_path. But before we copy the file, we should check if the file is in fact image, for that we "ll check another key called from our $ _FILES variable.

    // path were our avatar image will be stored $ avatar_path = $ mysqli-> real_escape_string ( "images /".$_ FILES [" avatar "] [" name "]); // make sure the file type is image if (preg_match ( "! Image!", $ _ FILES [ "avatar"] [ "type"])) (// copy image to images / folder if (copy ($ _ FILES [ " avatar "] [" tmp_name "], $ avatar_path)) ())

    The preg_match function matches the image from the [ "type"] key of $ _FILES array, we then use copy () function to copy our image file which takes in two parameters. The first one is the source file path which is our [ "tmp_name"] directory and the second one is the destination path which is our "images / guldan.png" file path.

    Saving User Data in a MySQL Database

    We can now set some session variables which we "ll need on the next page, which are username and avatar_path, and we" ll also create the SQL query which will insert all the submitted data into MySQL database:

    if (copy ($ _ FILES [ "avatar"] [ "tmp_name"], $ avatar_path)) (// set session variables to display on welcome page $ _SESSION [ "username"] = $ username; $ _SESSION [ "avatar"] = $ avatar_path; // create SQL query string for inserting data into the database $ sql = "INSERT INTO users (username, email, password, avatar)". "VALUES (" $ username "," $ email "," $ password "," $ avatar_path ")";)

    The final step is turn our query, using the query () method and check if it "s successful. If it is, that means the user data has been saved in the" users "table successfully! We then set the final session variable $ _SESSION [ "message"] and redirect the user to the welcome.php page using the header () function:

    // check if mysql query is successful if ($ mysqli-> query ($ sql) === true) ($ _SESSION [ "message"] = "Registration succesful! Added $ username to the database!"; // redirect the user to welcome.php header ( "location: welcome.php");)

    That "s pretty much all we need for the validation, we just need to add all the" else "keywords in case things don" t go as planned from all the if statements we have created. Here is what the full code for validate.php looks so far:

    / * Validate.php * / // the form has been submitted with post if ($ _SERVER [ "REQUEST_METHOD"] == "POST") (// two passwords are equal to each other if ($ _POST [ "password"] == $ _POST [ "confirmpassword"]) (// define other variables with submitted values ​​from $ _POST $ username = $ mysqli-> real_escape_string ($ _ POST [ "username"]); $ email = $ mysqli-> real_escape_string ($ _POST [ "email"]); // md5 hash password for security $ password = md5 ($ _ POST [ "password"]); // path were our avatar image will be stored $ avatar_path = $ mysqli-> real_escape_string ( "images /".$_FILES["avatar"]["name "]); // make sure the file type is image if (preg_match ("! image! ", $ _ FILES [" avatar "] [" type "])) (// copy image to images / folder if (copy ($ _ FILES [ "avatar"] [ "tmp_name"], $ avatar_path)) (// set session variables to display on welcome page $ _SESSION [ "username"] = $ username; $ _SESSION [ "avatar"] = $ avatar_path; // insert user data into database $ sql = "INSERT INTO users (username, email, password, avatar)". "VALUES (" $ use rname "," $ email "," $ password "," $ avatar_path ")"; // check if mysql query is successful if ($ mysqli-> query ($ sql) === true) ($ _SESSION [ "message"] = "Registration successful!". "Added $ username to the database!"; / / redirect the user to welcome.php header ( "location: welcome.php");)))))

    Setting Session Error Messages When Things Go Wrong

    Let "s go ahead and add all the else statements at once where we simply set the $ _SESSION [" message "] error messages which will be printed out when any of our if statements fail. Add the following code right after the last if statement where we checked for successful mysqli query and within the last curly bracket like this:

    If ($ mysqli-> query ($ sql) === true) ($ _SESSION [ "message"] = "Registration succesful!". "Added $ username to the database!"; Header ( "location: welcome.php" );) else ($ _SESSION [ "message"] = "User could not be added to the database!";) $ mysqli-> close (); ) Else ($ _SESSION [ "message"] = "File upload failed!";)) Else ($ _SESSION [ "message"] = "Please only upload GIF, JPG or PNG images!";)) Else ($ _SESSION [ "message"] = "Two passwords do not match!";)) // if ($ _SERVER [ "REQUEST_METHOD"] == "POST")

    The session message will then display the error message in the div tag where we put our $ _SESSION [ "message"] if you recall:

    Below is an example of what the error message is going to look like when two passwords don "t match. Feel free to play around with it to trigger other error messages:


    Creating User Profile Welcome Page

    We "re now done with the validate.php. The final step is to create welcome.php page which will display the username, avatar image and some users that have already been registered previously along with their own user names and mini avatar thumbnails. Here is what the complete welcome.php should look like, I will explain parts of it that may be confusing:

    ">
    Welcome query ($ sql); ?>
    All registered users:fetch_assoc ()) (echo "
    ". $ Row [" username "]."
    "; Echo"
    "; } ?>

    The $ _SESSION variable part from above should be easy to understand, we simply transfer over the variables from our validate.php page to this welcome.php page, if you "re still confused by that, please check out page for complete break down.

    Working with MySQL Result Object

    Whenever we use "SELECT" statement in our SQL query and then run that SQL with $ mysqli-> query ($ sql) command, the returned value is a MySQL result object. Once we have the result object, there are a few methods that become available so we can further start working with the data.

    $ Sql ​​= "SELECT username, avatar FROM users"; $ Result = $ mysqli-> query ($ sql); // $ result = mysqli_result object

    One of those methods is $ result-> fetch_assoc () which fetches the current row and returns an array with all the row data. So we "re putting that in a conditional expression, which will become false when it reaches the last row in the result set, and storing the returned value from $ result-> fetch_assoc () inside the $ row variable.

    // returns associative array of fetched row while ($ row = $ result-> fetch_assoc ()) (echo "

    ". $ Row [" username "]."
    "; Echo"
    "; }

    Conclusion

    And that "s how we" re able to access $ row [ "username"] and $ row [ "avatar"] from the associative array that is being returned, of the users that have already been registered previously and live in our users database table!

    The profile welcome page should now look very similar to the one shown in the very beginning of this lesson, and the form is now complete, good job! Please post any questions you may have in the comments below.