Good day friends! Let's take a look at user registration in PHP. First, let's define the conditions for our user registration:

  • The password is encrypted using an algorithm MD5
  • The password will be "salt"
  • Login busy check
  • User activation by letter.
  • Recording and storage of data in DBMS MySQL

To write this script, we need to understand what user registration is. User registration is the acquisition of real user data, processing and storage of data.

In simple words, registration is just a record and storage of certain data by which we can authorize the user in our case - this is the Login and Password.

Authorization - granting a certain person or group of persons the rights to perform certain actions, as well as the process of verifying these rights when trying to perform these actions. Simply put, with the help of authorization, we can restrict access to a particular content on our site.

Let's take a look at the script directory structure to implement our login with authorization. We need to break scripts into logical parts. We placed the registration and authorization modules in a separate directory. We will also place the database connection in separate directories. MySQL, file with custom functions, style file css and our template HTML. This structure allows you to quickly navigate through scripts. Imagine that you have a big site with a bunch of modules and so on. and if there is no order, it will be very difficult to find something in such a mess.

Since we will store all data in DBMS MySQL, then let's create a small table in which we will store registration data.

First you need to create a table in the database. Let's call the table bez_reg Where bez is the table prefix, and reg table name.

Table structure: bez_reg

-- -- `bez_reg` table structure -- 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 ;

Now let's create the main scripts for further work.

INDEX.PHP FILE

CONFIG.PHP FILE

"); ?>

File 404.HTML

Error 404

Error 404

There was a 404 error on the page

Return

BD.PHP file

INDEX.HTML FILE

PHP MySQL user registration with activation email

FUNCT.PHP FILE

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

  • ".$val."
  • "."\n"; ) else $err .= "
  • ".$data."
  • "."\n"; $err .= ""."\n"; return $err; ) /**Simple MySQL query wrapper * @param string $sql */ function mysqlQuery($sql) ( $res = mysql_query($sql); /* Check result This is shows the actual query sent to MySQL as well as the error.*/ if(!$res) ( $message = "Bad query: " . mysql_error() . "\n"; $message .= "Entire query : " . $sql; die($message); ) return $res; ) /**Simple salt generator * @param string $sql */ function salt() ( $salt = substr(md5(uniqid()), - 8); return $salt; )

    Let's start writing registration. To begin with, we will need to make a registration form template so that the user can enter his data for processing. Next, we will need to write the form handler itself, which will check the correctness of the user's entered data. After the data is successfully verified, we write it to our database and send an email to the user to activate his account.

    REG.PHP FILE

    You have successfully registered! Please activate your account!!"; //Activate the account if(isset($_GET["key"])) ( //Check the key $sql = "SELECT * FROM `". BEZ_DBPREFIX ."reg` WHERE `active_hex` = "". escape_str( $_GET["key"]) ."""; $res = mysqlQuery($sql); if(mysql_num_rows($res) == 0) $err = "Activation key is invalid!"; //Check for errors and display to the user if(count($err) > 0) echo showErrorMessage($err); else ( //Get the user's address $row = mysql_fetch_assoc($res); $email = $row["login"]; //Activate the account user $sql = "UPDATE `".BEZ_DBPREFIX ."reg` SET `status` = 1 WHERE `login` = "".$email ."""; $res = mysqlQuery($sql); //Send activation email $title = "Your account at http://website has been successfully activated"; $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 = "Email entered incorrectly"."\n"; ) if(empty($_POST[ "pass"])) $err = "Password field cannot be empty"; if(empty($_POST["pass2"])) $err = "Password confirmation field cannot be empty"; //Check for errors and display to the user if(count($err) > 0) echo showErrorMessage($err); else ( /*Continue to check the entered data Check for matching passwords*/ if($_POST["pass"] != $_POST["pass2" ]) $err = "Passwords do not match"; //Check for errors and display to the user if(count($err) > 0) echo showErrorMessage($err); else ( /*Check if we have such a user in the database* / $sql = "SELECT `login` FROM `".BEZ_DBPREFIX ."reg` WHERE `login` = "".escape_str($_POST["email"]) ."""; $res = mysqlQuery($sql); if(mysql_num_rows($res) > 0) $err = "Sorry Login: ". $_POST["email"] ." busy!"; //Check for errors and display to the user if(count($err) > 0) echo showErrorMessage($err); else ( //Get the HASH of the salt $salt = salt(); //Salt the password $pass = md5(md5($_POST["pass"]).$salt); /*If all goes well, write data to the database*/ $sql = "INSERT INTO `". BEZ_DBPREFIX ."reg` VALUES("", "" .escape_str($_POST["email"]) ."", "". $pass ."", "". $salt ."", "". md5($salt) ."", 0)"; $ res = mysqlQuery($sql); //Send activation email $url = BEZ_HOST ."less/reg/?mode=reg&key=". md5($salt); $title = "Registration on http:/ /website"; $message = "Для активации Вашего акаунта пройдите по ссылке ". $url .""; sendMessageMail($_POST["email"], BEZ_MAIL_AUTOR, $title, $message); //Сбрасываем параметры header("Location:". BEZ_HOST ."less/reg/?mode=reg&status=ok"); exit; } } } } ?>!}

    REG_FORM.HTML FILE

    PHP MySQL user registration with activation email

    Email *:
    Password *:
    Password confirmation *:

    Fields with an icon * required

    Since our user registration is ready, it's time to write authorization. We will create a form for user authorization, then we will write an authorization form handler and, finally, we will make a script show.php which will show us whether we are authorized in the system or not.

    AUTH.PHP FILE

    0) echo showErrorMessage($err); else ( /*Create a database fetch query to authenticate the user*/ $sql = "SELECT * FROM `". BEZ_DBPREFIX ."reg` WHERE `login` = "". escape_str($_POST["email"]) ."" AND `status` = 1"; $res = mysqlQuery($sql); //If login matches, check password if(mysql_num_rows($res) > 0) ( //Get data from table $row = mysql_fetch_assoc( $res); if(md5(md5($_POST["pass"]).$row["salt"]) == $row["pass"]) ( $_SESSION["user"] = true; // Reset parameters header("Location:". BEZ_HOST ."less/reg/?mode=auth"); exit; ) else echo showErrorMessage("Wrong password!"); ) else echo showErrorMessage("Login ". $_POST["email"] ." not found!"); ) ) ?>

    For those who have the latest version of PHP, I post this script using PDO because extension MySQL is deprecated and has been removed from the new version of PHP. Download registration and authorization php mysql pdo

    The archive was updated on February 24, 2015.

    Attention: If you are using this script on a local server like DENWER,XAMPP, then you should not wait for letters to your mailbox. Letters are in the stub sendmail. IN Denver you can find them along the way Z:\tmp\!sendmail\ You can open these files in any email client.

    In this article, you will learn how to create a registration and authorization form using HTML, JavaScript, PHP and MySql. Such forms are used on almost every site, regardless of its type. They are created for the forum, and for the online store and for social networks (such as Facebook, Twiter, Odnoklassniki) and for many other types of sites.

    If you have a site on your local computer, then I hope you already have . Nothing will work without it.

    Creating a Table in the Database

    In order to implement user registration, we first need a Database. If you already have it, then great, otherwise, you need to create it. In the article, I explain in detail how to do this.

    And so, we have a Database (abbreviated DB), now we need to create a table users in which we will add our registered users.

    How to create a table in the database, I also explained in the article. Before creating a table, we need to define what fields it will contain. These fields will match the fields from the registration form.

    So, we thought, imagined what fields our form will have and create a table users with these fields:

    • id- Identifier. Field id should be in every table from the database.
    • first_name- To save the name.
    • last_name- To save the last name.
    • email- To save the postal address. We will use e-mail as a login, so this field must be unique, that is, have a UNIQUE index.
    • email_status- A field to indicate whether the mail is confirmed or not. If the mail is confirmed, then it will have a value of 1, otherwise the value of 0.
    • password- To save the password.


    If you want your registration form to have some more fields, you can add them here as well.

    That's it, our table users ready. Let's move on to the next step.

    Database connection

    We have created the database, now we need to connect to it. We will connect using the MySQLi PHP extension.

    In the folder of our site, create a file with the name dbconnect.php, and in it we write the following script:

    Database connection error. Error Description: ".mysqli_connect_error()."

    "; exit(); ) // Set the connection encoding $mysqli->set_charset("utf8"); //For convenience, add a variable here that will contain the name of our site $address_site = "http://testsite.local" ; ?>

    This file dbconnect.php will need to be connected to form handlers.

    Pay attention to the variable $address_site, here I have indicated the name of my test site, which I will work on. You accordingly indicate the name of your site.

    Site structure

    Now let's take a look at the HTML structure of our site.

    Move the site header and footer to separate files, header.php And footer.php. We will connect them on all pages. Namely, on the main (file index.php), to the page with the registration form (file form_register.php) and on the page with the authorization form (file form_auth.php).

    Block with our links, registration And authorization, add to the header of the site so that they are displayed on all pages. One link will enter on registration form page(file form_register.php) and the other to the page with authorization form(file form_auth.php).

    Content of header.php file:

    The name of our site

    As a result, our main page looks like this:


    Of course, your site may have a completely different structure, but this is not important for us now. The main thing is that there are links (buttons) for registration and authorization.

    Now let's move on to the registration form. As you already understood, we have it in the file form_register.php.

    We go to the Database (in phpMyAdmin), open the table structure users and see what fields we need. So, we need fields for entering a first and last name, a field for entering a postal address (Email) and a field for entering a password. And for security purposes, we will add a captcha input field.

    On the server, as a result of processing the registration form, various errors may occur due to which the user will not be able to register. Therefore, in order for the user to understand why the registration fails, it is necessary to display messages about these errors to him.

    Before displaying the form, we add a block to display error messages from the session.

    And another moment, if the user is already authorized, and for the sake of interest, he enters the registration page directly by writing in the address bar of the browser website_url/form_register.php, then in this case, instead of the registration form, we will display a title for it that it is already registered.

    In general, the file code form_register.php we got it like this:

    You are already registered

    In the browser, the registration page looks like this:


    By using required attribute, we have made all fields mandatory.

    Pay attention to the registration form code where captcha is displayed:


    We in the value of the src attribute for the image, specified the path to the file captcha.php, which generates this captcha.

    Let's look at the code of the file captcha.php:

    The code is well commented, so I'll just focus on one point.

    Inside a function imageTtfText(), the path to the font is specified verdana.ttf. So for the captcha to work correctly, we must create a folder fonts, and put the font file there verdana.ttf. You can find and download it from the Internet, or take it from the archive with the materials of this article.

    We are done with the HTML structure, it's time to move on.

    Validating email with jQuery

    Any form needs validation of the entered data, both on the client side (using JavaScript, jQuery) and on the server side.

    We must pay special attention to the Email field. It is very important that the entered email address is valid.

    For this input field, we set the type email (type="email"), this warns us a little bit against incorrect formats. But, this is not enough, because through the code inspector that the browser provides us, you can easily change the value of the attribute type With email on text, and that's it, our check will no longer be valid.


    And in that case, we have to make a more reliable check. To do this, we will use the jQuery library from JavaScript.

    To connect the jQuery library, in the file header.php between tags , before the closing tag , add this line:

    Right after this line, add the email validation check code. Here we add the code for checking the length of the entered password. It must be at least 6 characters long.

    With the help of this script, we check the entered email address for validity. If the user entered the wrong Email, then we display an error about it and deactivate the submit button of the form. If everything is fine, then we remove the error and activate the submit button of the form.

    And so, with the form validation on the client side, we are done. Now we can send it to the server, where we will also do a couple of checks and add data to the database.

    User registration

    We send the form for processing to the file register.php, via the POST method. The name of this handler file, specified in the attribute value action. And the send method is specified in the attribute value method.

    Open this file register.php and the first thing we need to do is write a session launch function and include the file we created earlier dbconnect.php(In this file, we made a connection to the database). And yet, immediately declare the cells error_messages And success_messages in the session global array. IN error_mesages we will record all error messages that occur during form processing, and in success_messages Let's write happy messages.

    Before continuing, we must check whether the form was submitted at all. An attacker can look at the value of an attribute action from the form, and find out which file is processing this form. And he may come up with the idea to go directly to this file by typing the following address in the address bar of the browser: http://site_site/register.php

    So we need to check if there is a cell in the global POST array whose name matches the name of our "Register" button from the form. Thus, we check whether the "Register" button was pressed or not.

    If an attacker tries to go directly to this file, he will receive an error message. I remind you that the $address_site variable contains the name of the site and it was declared in the file dbconnect.php.

    Error! main page .

    "); } ?>

    The captcha value in the session was added during its generation, in the file captcha.php. As a reminder, I will show once again this piece of code from the file captcha.php, where the captcha value is added to the session:

    Now let's get to the test itself. In file register.php, inside the if block, where we check whether the "Register" button was pressed, or rather, where the comment " // (1) Place for the next piece of code"we write:

    //Check the received captcha //Trim spaces from the beginning and from the end of the string $captcha = trim($_POST["captcha"]); if(isset($_POST["captcha"]) && !empty($captcha))( //Compare the received value with the value from the session. if(($_SESSION["rand"] != $captcha) && ($_SESSION ["rand"] != ""))( // If the captcha is not correct, then return the user to the registration page, and there we will display an error message that he entered the wrong captcha. $error_message = "

    Error! You entered the wrong captcha

    "; // Save the error message to the session. $_SESSION["error_messages"] = $error_message; // Return the user to the registration page header("HTTP/1.1 301 Moved Permanently"); header("Location: ".$address_site ."/form_register.php"); //Stop the script exit(); ) // (2) Place for the next piece of code )else( //If the captcha is not passed or it is empty exit("

    Error! There is no verification code, that is, the captcha code. You can go to the main page.

    "); }

    Next, we need to process the received data from the POST array. First of all, we need to check the contents of the global POST array, that is, whether there are cells there whose names match the names of the input fields from our form.

    If the cell exists, then we trim the spaces from the beginning and from the end of the string from this cell, otherwise, we redirect the user back to the page with the registration form.

    Further, after the spaces have been trimmed, we add a string to the variable and check this variable for emptiness, if it is not empty, then move on, otherwise we redirect the user back to the page with the registration form.

    Paste this code in the specified location // (2) Place for the next piece of code".

    /* Check if the global array $_POST contains data submitted from the form and enclose the submitted data in regular variables.*/ if(isset($_POST["first_name"]))( // Trim spaces from the beginning and end of the string $first_name = trim($_POST["first_name"]); //Check if the variable is empty if(!empty($first_name))( // For safety, convert special characters to HTML entities $first_name = htmlspecialchars($first_name, ENT_QUOTES) ; )else( // Save the error message to the session. $_SESSION["error_messages"] .= "

    Enter your name

    Name field missing

    "; //Return the user to the registration page header("HTTP/1.1 301 Moved Permanently"); header("Location: ".$address_site."/form_register.php"); //Stop the script exit(); ) if( isset($_POST["last_name"]))( // Trim spaces from the beginning and end of the string $last_name = trim($_POST["last_name"]); if(!empty($last_name))( // For safety , convert special characters to HTML entities $last_name = htmlspecialchars($last_name, ENT_QUOTES); )else( // Save the error message to the session. $_SESSION["error_messages"] .= "

    Enter your last name

    "; //Return the user to the registration page header("HTTP/1.1 301 Moved Permanently"); header("Location: ".$address_site."/form_register.php"); //Stop the script exit(); ) )else ( // Save the error message to the session. $_SESSION["error_messages"] .= "

    Name field missing

    "; //Return the user to the registration page header("HTTP/1.1 301 Moved Permanently"); header("Location: ".$address_site."/form_register.php"); //Stop the script exit(); ) if( isset($_POST["email"]))( // Trim spaces from the beginning and end of the string $email = trim($_POST["email"]); if(!empty($email))( $email = htmlspecialchars ($email, ENT_QUOTES); // (3) Place of code to check the format of the email address and its uniqueness )else( // Save the error message to the session. $_SESSION["error_messages"] .= "

    Enter your email

    "; //Return the user to the registration page header("HTTP/1.1 301 Moved Permanently"); header("Location: ".$address_site."/form_register.php"); //Stop the script exit(); ) )else ( // Save the error message to the session. $_SESSION["error_messages"] .= "

    "; //Return the user to the registration page header("HTTP/1.1 301 Moved Permanently"); header("Location: ".$address_site."/form_register.php"); //Stop the script exit(); ) if( isset($_POST["password"]))( // Trim spaces from the beginning and end of the string $password = trim($_POST["password"]); if(!empty($password))( $password = htmlspecialchars ($password, ENT_QUOTES); //Encrypt the password $password = md5($password."top_secret"); )else( // Save the error message to the session. $_SESSION["error_messages"] .= "

    Enter your password

    "; //Return the user to the registration page header("HTTP/1.1 301 Moved Permanently"); header("Location: ".$address_site."/form_register.php"); //Stop the script exit(); ) )else ( // Save the error message to the session. $_SESSION["error_messages"] .= "

    "; //Return the user to the registration page header("HTTP/1.1 301 Moved Permanently"); header("Location: ".$address_site."/form_register.php"); //Stop the script exit(); ) // (4) Place for the code for adding a user to the database

    The field is of particular importance. email. We have to check the format of the received mailing address and its uniqueness in the database. That is, whether a user with the same email address is already registered.

    At the specified location" // (3) Place of code to check the format of the postal address and its uniqueness" add the following code:

    //Check the format of the received email address using the regular expression $reg_email = "/^**@(+(*+)*\.)++/i"; //If the format of the received email address does not match the regular expression if(!preg_match($reg_email, $email))( // Save the error message to the session. $_SESSION["error_messages"] .= "

    You entered an invalid email

    "; //Return the user to the registration page header("HTTP/1.1 301 Moved Permanently"); header("Location: ".$address_site."/form_register.php"); //Stop the script exit(); ) // Check if there is already such an address in the database $result_query = $mysqli->query("SELECT `email` FROM `users` WHERE `email`="".$email."""); If there are exactly one rows, then the user with this email address is already registered if($result_query->num_rows == 1)( //If the result is not false if(($row = $result_query->fetch_assoc()) != false) ( // Save the error message to the session. $_SESSION["error_messages"] .= "

    User with this email address is already registered

    "; //Return the user to the registration page header("HTTP/1.1 301 Moved Permanently"); header("Location: ".$address_site."/form_register.php"); )else( //Save the error message to the session .$_SESSION["error_messages"] .= "

    Error in database query

    "; //Return the user to the registration page header("HTTP/1.1 301 Moved Permanently"); header("Location: ".$address_site."/form_register.php"); ) /* close the selection */ $result_query-> close(); //Stop the script exit(); ) /* close the selection */ $result_query->close();

    And so, we are done with all the checks, it's time to add the user to the database. At the specified location" // (4) Place for the code for adding a user to the database" add the following code:

    //Query to add a user to the database $result_query_insert = $mysqli->query("INSERT INTO `users` (first_name, last_name, email, password) VALUES ("".$first_name."", "".$last_name." ", "".$email."", "".$password."")"); if(!$result_query_insert)( // Save the error message to the session. $_SESSION["error_messages"] .= "

    Error request to add a user to the database

    "; //Return the user to the registration page header("HTTP/1.1 301 Moved Permanently"); header("Location: ".$address_site."/form_register.php"); //Stop the script exit(); )else( $_SESSION["success_messages"] = "

    Registration completed successfully!!!
    Now you can log in using your username and password.

    "; //Send the user to the login page header("HTTP/1.1 301 Moved Permanently"); header("Location: ".$address_site."/form_auth.php"); ) /* Complete the request */ $result_query_insert-> close(); //Close the database connection $mysqli->close();

    If an error occurs in the request to add a user to the database, we add a message about this error to the session and return the user to the registration page.

    Otherwise, if everything went well, we also add a message to the session, but it is already more pleasant, namely, we tell the user that the registration was successful. And we redirect it to the page with the authorization form.

    The script for checking the format of the email address and the length of the password is in the file header.php, so it will affect fields from that form as well.

    The session is also started in the file header.php, so in the file form_auth.php the session does not need to be started, because we get an error.


    As I said, the script for checking the format of the mail address and the length of the password also works here. Therefore, if the user enters the wrong email address or short password, he will immediately receive an error message. A button to come in will become inactive.

    After fixing the errors, the button to come in becomes active and the user can submit the form to the server where it will be processed.

    User authorization

    To attribute value action the authorization form has a file auth.php, which means that the form will be processed in this file.

    So let's open the file auth.php and write the code to process the authorization form. The first thing to do is start the session and include the file dbconnect.php to connect to the database.

    //Declare a cell to add errors that may occur during form processing. $_SESSION["error_messages"] = ""; //Declare a cell to add successful messages $_SESSION["success_messages"] = "";

    /* Check if the form was submitted, that is, if the Login button was clicked. If yes, then we go further, if not, then we will display an error message to the user, stating that he went to this page directly. */ if(isset($_POST["btn_submit_auth"]) && !empty($_POST["btn_submit_auth"]))( //(1) Place for the next piece of code )else( exit("

    Error! You have accessed this page directly, so there is no data to process. You can go to the main page.

    "); }

    //Check the received captcha if(isset($_POST["captcha"]))( //Trim spaces from the beginning and end of the string $captcha = trim($_POST["captcha"]); if(!empty($captcha ))( //Compare the received value with the value from the session. if(($_SESSION["rand"] != $captcha) && ($_SESSION["rand"] != ""))( // If the captcha is invalid , then we return the user to the authorization page, and there we will display an error message that he entered the wrong captcha. $error_message = "

    Error! You entered the wrong captcha

    "; // Save the error message to the session. $_SESSION["error_messages"] = $error_message; // Return the user to the authorization page header("HTTP/1.1 301 Moved Permanently"); header("Location: ".$address_site ."/form_auth.php"); //Stop the script exit(); ) )else( $error_message = "

    Error! The captcha input field must not be empty.

    "; // Save the error message to the session. $_SESSION["error_messages"] = $error_message; // Return the user to the authorization page header("HTTP/1.1 301 Moved Permanently"); header("Location: ".$address_site ."/form_auth.php"); //Stop the script exit(); ) //(2) Place for processing the mail address //(3) Place for processing the password //(4) Place for making a query to the database )else ( //If captcha is not passed exit("

    Error! There is no verification code, that is, the captcha code. You can go to the main page.

    "); }

    If the user has entered the verification code correctly, then we move on, otherwise we return him to the authorization page.

    Email address verification

    // Trim spaces from the beginning and end of the string $email = trim($_POST["email"]); if(isset($_POST["email"]))( if(!empty($email))( $email = htmlspecialchars($email, ENT_QUOTES); //Check the format of the received email address using the regular expression $reg_email = " /^**@(+(*+)*\.)++/i"; //If the format of the received email address does not match the regular expression if(!preg_match($reg_email, $email))( // Save to the session error message.$_SESSION["error_messages"] .= "

    You entered an invalid email

    "; //Return the user to the authorization page header("HTTP/1.1 301 Moved Permanently"); header("Location: ".$address_site."/form_auth.php"); //Stop the script exit(); ) )else ( // Save the error message to the session. $_SESSION["error_messages"] .= "

    The field for entering the postal address (email) should not be empty.

    "; //Return the user to the registration page header("HTTP/1.1 301 Moved Permanently"); header("Location: ".$address_site."/form_register.php"); //Stop the script exit(); ) )else ( // Save the error message to the session. $_SESSION["error_messages"] .= "

    There is no field for entering Email

    "; //Return the user to the authorization page header("HTTP/1.1 301 Moved Permanently"); header("Location: ".$address_site."/form_auth.php"); //Stop the script exit(); ) // (3) Place for password processing

    If the user has entered an email address in the wrong format or the value of the email address field is empty, then we return him to the authorization page, where we display a message about this.

    Password check

    The next field to process is the password field. To the designated place" //(3) Place for password processing", we write:

    If(isset($_POST["password"]))( // Trim spaces from the beginning and end of the string $password = trim($_POST["password"]); if(!empty($password))( $password = htmlspecialchars($password, ENT_QUOTES); // Encrypt the password $password = md5($password."top_secret"); )else( // Save the error message to the session. $_SESSION["error_messages"] .= "

    Enter your password

    "; //Return the user to the registration page header("HTTP/1.1 301 Moved Permanently"); header("Location: ".$address_site."/form_auth.php"); //Stop the script exit(); ) )else ( // Save the error message to the session. $_SESSION["error_messages"] .= "

    There is no field for entering a password

    "; //Return the user to the registration page header("HTTP/1.1 301 Moved Permanently"); header("Location: ".$address_site."/form_auth.php"); //Stop the script exit(); )

    Here, using the md5 () function, we encrypt the received password, since in the database we have passwords in encrypted form. Additional secret word in encryption, in our case " top_secret" must be the one that was used when registering the user.

    Now you need to make a query to the database on a user selection whose mail address is equal to the received mail address and the password is equal to the received password.

    //Query to the database on the user's selection. $result_query_select = $mysqli->query("SELECT * FROM `users` WHERE email = "".$email."" AND password = "".$password."""); if(!$result_query_select)( // Save the error message to the session. $_SESSION["error_messages"] .= "

    Query error on user selection from database

    "; //Return the user to the registration page header("HTTP/1.1 301 Moved Permanently"); header("Location: ".$address_site."/form_auth.php"); //Stop the script exit(); )else( //Check if there is no user with such data in the database, then display an error message if($result_query_select->num_rows == 1)( // If the entered data matches the data from the database, then save the login and password to the session array. $_SESSION["email"] = $email; $_SESSION["password"] = $password; //Return the user to the main page header("HTTP/1.1 301 Moved Permanently"); header("Location: ".$address_site ."/index.php"); )else( // Save the error message to the session. $_SESSION["error_messages"] .= "

    Wrong username and/or password

    "; //Return the user to the authorization page header("HTTP/1.1 301 Moved Permanently"); header("Location: ".$address_site."/form_auth.php"); //Stop the script exit(); ) )

    Site exit

    And the last thing we implement is exit procedure. At the moment, in the header we display links to the authorization page and the registration page.

    In the site header (file header.php), using the session, we check if the user is already logged in. If not, then we display the registration and authorization links, otherwise (if it is authorized), then instead of the registration and authorization links we display the link Exit.

    Modified piece of code from file header.php:

    Registration

    Exit

    When you click on the exit link from the site, we get into the file logout.php, where we simply destroy the cells with the email address and password from the session. After that, we return the user back to the page on which the link was clicked exit.

    File Code logout.php:

    That's all. Now you know how implement and process registration and authorization forms user on your site. These forms are found on almost every site, so every programmer should know how to create them.

    We also learned how to validate input data, both on the client side (in the browser, using JavaScript, jQuery) and on the server side (using the PHP language). We also learned implement logout procedure.

    All scripts are tested and working. You can download the archive with the files of this small site from this link.

    In the future I will write an article where I will describe. And I also plan to write an article where I will explain (without reloading the page). So, in order to be aware of the release of new articles, you can subscribe to my site.

    If you have any questions, please contact, also, if you notice any mistake in the article, please let me know.

    Lesson Plan (Part 5):

    1. Creating an HTML Structure for the Authorization Form
    2. We process the received data
    3. We display the user's greeting in the header of the site

    Liked the article?

    Laravel requires Composer to manage the project dependencies. So before installing Laravel, make sure you have Composer installed on your system. In case you are hearing about Composer for the first time, it's a dependency management tool for php similar to node's npm.

    To install Composer on your machine, check this post:

    Installing Laravel on Windows:

    Follow the below steps to install laravel on windows machine. No matter you have xampp/wamp stack, it works for both. On WAMP, make sure to install laravel on "www" folder and on XAMPP, obviously the "htdocs".

    STEP-1) Open "htdocs" folder on XAMPP, hold SHIFT key and right click on the folder, and choose "open command window here". Alternatively, you can open command window and change directory to "xampp/htdocs".

    STEP-2) Enter the following command.

    Composer create-project laravel/laravel my_laravel_site --prefer-dist

    Here "my_laravel_site" is the folder name where laravel files will be installed. Change this to your liking.

    STEP-3) Now it "s time to be patient as laravel installation is going to take some time.

    STEP-4) Once installed, change directory to "my_laravel_site" (cd "my_laravel_site") on the command prompt and enter the below command.

    php artisan serve

    STEP-5) This will show a message something like, "Laravel development server started:" along with an url.

    STEP-6) Copy and paste the url on the browser. If things go right, you "d see the laravel welcome screen.

    STEP-7) Done! You have successfully installed laravel on windows machine and ready to go with.

    Setting Application Key:

    Laravel requires little configuration after installation. It requires you to set the application key. This is a random string of 32 characters long used for encrypting session and other sensitive data. Usually this will be set automatically when you install laravel via composer or laravel installer.

    In case it"s not set, you have to do it manually. First make sure to rename the ".env.example" file to ".env" on your application root. Then open command prompt and change to the laravel project folder. Now run the below command to generate the key.

    php artisan key:generate

    Copy this generated key to the APP_KEY variable on ".env" file. Save and you are done.

    Installing Specific Laravel Version:

    The above given method will make composer to download and install the latest version of laravel. If you want to install earlier versions of laravel on your machine, make sure to include the respective version number on create-project command.

    Composer create-project laravel/laravel=5.4 your-project-name --prefer-dist Read Also:

    Likewise you can easily install laravel using composer on windows. I hope you find this tutorial useful. Please share it on your social circle if you like it.

    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:

    register.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.