Создаем невероятную простую систему регистрации на PHP и MySQL. PHP сценарии обработки HTML форм Торговец users registration form html

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 Your Full Name*: Email Address*: UserName*: Password*:

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 !

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.

Доброго времени суток друзья! Давай с Вами рассмотрим регистрацию пользователей на 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

less/reg/?mode=auth">Войти

  • Description of Listing 4:

    We created a connection between the database and our webpages. But if you don’t know is it working or not so you use one thing more in the last check listing 5 for it.

    Listing 5 : checking the connection of database connectivity

    Description Listing 5:

    In the Listing 5 I just tried to show you that you can check and confirm the connection between the database and PHP. And one thing more we will not use Listing 5 code in our sing-up webpage. Because it’s just to make you understand how you can check the MySQL connection.

    Now we will write a PHP programming application to first check the availability of user and then store the user if he/she is a new user on the webpage.

    Listing 6 : connectivity-sign-up.php

    Description of connectivity-sign-up.php

    In this PHP application I used simplest way to create a sign up application for the webpages. As you can see first we create a connection like listing 4. And then we used two functions the first function is SignUP() which is being called by the if statement from the last of the application, where its first confirming the pressing of sign up button. If it is pressed then it will call the SingUp function and this function will use a query of SELECT to fetch the data and compare them with userName and email which is currently entered from the user. If the userName and email is already present in the database so it will say sorry you are already registered

    If the user is new as its currently userName and email ID is not present in the database so the If statement will call the NewUser() where it will store the all information of the new user. And the user will become a part of the webpage.



    Figure 3

    In the figure 3, user is entering data to sign up if the user is an old user of this webpage according to the database records. So the webpage will show a message the user is registered already if the user is new so the webpage will show a message the user’s registration is completed.



    Figure 4:

    As we entered data to the registration form (Figure 4), according to the database which userName and email we entered to the registration form for sing-up it’s already present in the database. So we should try a new userName and email address to sign-up with a new ID and Password.



    Figure 5

    In figure 5, it is confirming us that which userName and email id user has entered. Both are not present in the database records. So now a new ID and Password is created and the user is able to use his new ID and Password to get login next time.

    Conclusion:

    In this article we learnt the simplest way of creating a sign up webpage. We also learnt that how it deals with the database if we use PHP and MySQL. I tried to give you a basic knowledge about sign up webpage functionality. How it works at back end, and how we can change its look on front end. For any query don’t hesitate and comment.

    I am glad to post here my knowledge and techniques used in PHP and MySQL. As you all aware that PHP and MySQL are the most widely used Open Source for websites. Today’s millions of websites and applications are using these free software’s. Personally I feel that this could be next level for front end developers by using PHP and MySQL a HTML developer can make a website more dynamic. Let us discuss How to create a Basic registration form in PHP with database, Its simple and very useful for a basic website dynamic user dynamic registration. Every creative can implement its basic structure to their website. Now Just follow these simple steps and you will find that your first dynamic functional registration form with database entry on every form fill up.

    STEP 1: Create Database for inserting values Go to MySQL, Create database student; Qurey OK, 1 row affected (0.00 sec) mysql> use student Database changed mysql> create table student(id int,name varchar(40),email varchar(80),password varchar(40)); Query OK, 0 rows affected (0.05 sec) STEP 2: Front end code, Make HTML Structure of your registration form Make a new file registration.html we will make it in PHP later, the structure would be: REGISTRATION FORM USERNAME:
    EMAIL-ID:
    PASSWORD:
    RE-PASSWORD:
    STEP 3: For Database connectivity using MySQL Create a connect.php file for basic database connection use that default code as below STEP 4: Finally create a registration.php page to get value of all fields shown in HTML page Here a Front end developer can write some own code in PHP, Read the code and understand this basic structure line by line you will find it very easy. Conclusion By following step by step procedure provided above a basic registration form can be created. So best of luck for your first PHP code Get the code

    Процесс создания системы регистрации – это довольно большой объем работы. Вам нужно написать код, который бы перепроверял валидность 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-сайте, либо модернизировать ее, придерживаясь собственных требований.

    Похожие статьи
  • © 2024 karkywa.ru. Программы. Интернет. Безопасность. Компьютеры. Windows.