Godless auth registration php

10/05/2015 Romchik

Good day. In this article, we will use an example to analyze user registration in . Then activate the user by confirming his email address. And finally, user authorization in . But only active users should be authorized.

The first thing we will do is create a controller and a view for registration.

Creating a registration form

Go to the directory with the resources templates and create the auth subdirectory in it. Now in the auth folder we will create a file register.blade.php with the following code:

Registration

((--Errors--)) @if ($errors->has()) ×
    @foreach($errors->all() as $error)
  • ((( $error )))
  • @endforeach
@endif (!! csrf_field() ! Email Пароль Повторите пароль Отправить !}

I won’t explain the code above, everything is clear here.

App/Http/Controllers/Auth/AuthController.php

We will only override the AuthController.php controller methods. So, to display the registration form, there is a getRegister method. We do not touch this method.

Now let's move on to routes. Open the file:

And define the route to our method:

Route::get("auth/register", "Auth\AuthController@getRegister");

Now let's open our application in the browser. Great, we see the registration form.

User registration in

Let's immediately define the route for user registration. Let's go to the file:

App/Http/Controllers/routes.php

And add the following route:

Route::post("auth/register", "Auth\AuthController@postRegister");

Now let's create a table to store users. There is already a migration for this table, but it is not suitable for us. Let's change it. Let's go to the file:

Database/migrations/2014_10_12_create_users_table.php

And let's change the code:

In my case it looks like this:

Save bd.php .
Great! We have a table in the database and a connection to it. Now you can start creating a page on which users will leave their data.

3. Create a reg.php file with the contents (all comments inside):



Registration


Registration


Your login:




Your password:








4. Create a file that will enter data into the database and save the user. save_user.php (comments inside):

5. Now our users can register! Next, you need to create a “door” for already registered users to enter the site. index.php (comments inside) :




Home page


Home page


Your login:


Your password:






Register



OK it's all over Now! The lesson may be boring, but very useful. Only the idea of ​​registration is shown here, then you can improve it: add security, design, data fields, loading avatars, logging out of your account (to do this, simply destroy variables from the session with the unset function) and so on. Good luck!

I checked everything, it works properly!

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

If you have a website on your local computer, then I hope that you already have a local server installed and running. Without it, nothing will work.

Creating a table in the Database

In order to implement user registration, first of all we 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 as DB), now we need to create a table users in which we will add our registered users.

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

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

  • id- Identifier. Field id Every table in the database should have it.
  • first_name- To save the name.
  • last_name- To preserve the surname.
  • email- To save the postal address. We will use e-mail as a login, so this field must be unique, that is, have the UNIQUE index.
  • email_status- 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 is 0.
  • password- To save the password.


If you want your registration form to have some other fields, you can also add them here.

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

Database Connection

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

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

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

Notice the variable $address_site, here I indicated the name of my test site that I will be working on. Please indicate the name of your site accordingly.

Site structure

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

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

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

Contents of the header.php file:

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 understand, we have it on file form_register.php.

Go to the Database (in phpMyAdmin), open the table structure users and look at what fields we need. This means that we need fields for entering the first and last name, a field for entering the postal address (Email) and a field for entering the password. And for security purposes, we will add a field for entering a captcha.

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 registration fails, it is necessary to display messages about these errors.

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

And one more thing, if the user is already authorized, and out of curiosity he goes to the registration page directly by writing in the address bar of the browser site_address/form_register.php, then in this case, instead of the registration form, we will display a header stating that he is already registered.

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

You are already registered

In the browser, the page with the registration form looks like this:


Using the required attribute, we made all fields mandatory.

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


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

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

The code is well commented, so I will focus on just 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 place the font file there verdana.ttf. You can find it and download it from the Internet, or take it from the archive with the materials of this article.

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

Checking email validity using jQuery

Any form needs to check the validity 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 postal address is valid.

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


And in this case, we must do 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:

Immediately after this line, we will add the email validation code. Here we will add a code to check the length of the entered password. Its length must be at least 6 characters.

Using this script, we check the entered email address for validity. If the user entered an incorrect Email, we display an error message about this and disable the form submit button. If everything is fine, then we remove the error and activate the form submit button.

And so, we are done with form validation on the client side. 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 to the file for processing register.php, via the POST method. The name of this handler file is specified in the attribute value action. And the sending 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 connect the file we created earlier dbconnect.php(In this file we made a connection to the database). And also, let’s immediately declare the cells error_messages And success_messages in the global session array. IN error_mesages we will record all error messages that occur during form processing, and in succes_messages, we will record joyful messages.

Before we continue, we need to check if the form was submitted at all. An attacker can look at the attribute value action from the form, and find out which file is processing this form. And he may have the idea to go directly to this file by typing the following address in the browser’s address bar: http://site_address/register.php

So we need to check for a cell in the global POST array whose name matches the name of our "Register" button from the form. This way we check whether the "Register" button was clicked or not.

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

The captcha value in the session was added when it was generated, in the file captcha.php. As a reminder, I’ll show you this piece of code from the file again captcha.php, where the captcha value is added to the session:

Now let's proceed to the verification itself. In file register.php, inside the if block, where we check whether the "Register" button was clicked, or rather where the comment " is indicated" // (1) Space for the next piece of code"we write:

//Check the received captcha //Trim the spaces from the beginning and end of the line $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 we return the user to the registration page, and there we will display an error message to him 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, a 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 correspond to the names of the input fields from our form.

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

Next, after we have trimmed the spaces, we add the line to the variable and check this variable for emptyness; if it is not empty, then we move on, otherwise we redirect the user back to the page with the registration form.

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

/* Check if there is data sent from the form in the global array $_POST and wrap the submitted data in regular variables.*/ if(isset($_POST["first_name"]))( //Trim the spaces from the beginning and end of the string $first_name = trim($_POST["first_name"]); //Check the variable for emptiness 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 is 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 line $last_name = trim($_POST["last_name"]); if(!empty($last_name))( // For security , convert special characters into HTML entities $last_name = htmlspecialchars($last_name, ENT_QUOTES); )else( // Save the error message to the session. $_SESSION["error_messages"] .= "

Please 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"] .= "

Last name field is 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 line $email = trim($_POST["email"]); if(!empty($email))( $email = htmlspecialchars ($email, ENT_QUOTES); // (3) Code location for checking 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

Of particular importance is the field email. We must check the format of the received postal address and its uniqueness in the database. That is, is there any user with the same email address already registered?

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

//Check the format of the received email address using a 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 incorrect 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(); ) // We check whether such an address is already in the database. $result_query = $mysqli->query("SELECT `email` FROM `users` WHERE `email`="".$email."""); //If the number of received there are exactly one row, which means the user with this email address is already registered if($result_query->num_rows == 1)( //If the result obtained is not false if(($row = $result_query->fetch_assoc()) != false) ( // Save the error message to the session. $_SESSION["error_messages"] .= "

A 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"); ) /* closing the selection */ $result_query-> close(); //Stop the script exit(); ) /* closing 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 in request to add user to 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 authorization page header("HTTP/1.1 301 Moved Permanently"); header("Location: ".$address_site."/form_auth.php"); ) /* Completing the request */ $result_query_insert-> close(); //Close the connection to the database $mysqli->close();

If an error occurred 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 this time it’s 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 email address format and password length is in the file header.php, so it will also apply to fields from this form.

The session is also started in the file header.php, so in the file form_auth.php There is no need to start a session, because we will get an error.


As I already said, the script for checking the email address format and password length also works here. Therefore, if the user enters an incorrect 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 will be able to submit the form to the server, where it will be processed.

User authorization

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

And so, open the file auth.php and write code to process the authorization form. The first thing you need to do is start a session and connect the file dbconnect.php to connect to the database.

When you click on the exit link from the site, we are taken to a file logout.php, where we simply destroy the cells with the email address and password from the session. After this, 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 to implement and process user registration and authorization forms on your website. These forms are found on almost every website, 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 PHP). We also learned how to implement a procedure for leaving the site.

All scripts have been tested and are 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 stay informed about the release of new articles, you can subscribe to my website.

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

Lesson Plan (Part 5):

  • Creating an HTML structure for the authorization form
  • We process the received data
  • We display the user's greeting in the site header
  • Did you like the article?

    We will learn how to do simple user authentication on the site. The site may have pages only for authorized users, and they will function fully if we add our authentication block to them. To create it, you need a MySQL database. It can have 5 columns (minimum), or more if you want to add information about users. Let's call the database “Userauth”.

    Let's create the following fields in it: ID for counting the number of users, UID for the user's unique identification number, Username for the user's name, Email for his email address and Password for the password. You can use your existing database to authorize the user, just, as in the case of a new database, create the following table in it.

    MySQL Code

    CREATE TABLE `users` (`ID` int (11) NOT NULL AUTO_INCREMENT, `UID` int (11) NOT NULL, `Username` text NOT NULL, `Email` text NOT NULL, `Password` text NOT NULL, PRIMARY KEY (`ID`)) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;

    Now let's create the file "sql.php". It is responsible for connecting to the database. This code, firstly, creates variables for the server and the user when he connects to the server. Secondly, it will select the database, in this case "USERAUTH". This file must be included in "log.php" and "reg.php" to access the database.

    PHP code

    Next is the login page, let it be called “login.php”. First, it checks the entered data for errors. The page has fields for username, password, submit button and registration link. When the user clicks the "Login" button, the form will be processed by the code from the "log.php" file and then logged in.

    PHP code

    Login form

    Username
    Password
    Registration

    Then we write a script to log into the system. Let's call it "log.php". It has a function to clean up the input data from SQL injections that can ruin your script. Secondly, it receives the form data and checks it for correctness. If the input data is correct, the script sends the user to the authorized users page, if not, it sets errors and sends the user to the login page.

    PHP code

    Let's make a registration page, call it "register.php". It is similar to the login page, only it has a few more fields, and instead of a registration link, there is a link to login.php in case the user already has an account.

    PHP code

    Registration form

    Username
    Email
    Password
    Repeat password
    I have an account

    Now we will create a registration script in the file "reg.php". It will include "sql.php" to connect to the database. The same function is used as in the login script to clear the input field. Variables are set for possible errors. Next is a function to create a unique identifier that has never been provided before. The data from the registration form is then extracted and verified. A check is made to ensure that the email address is in the correct format and that the password is re-entered correctly. The script then checks to see if there is a user with the same name in the database and, if so, reports an error. Finally, the code adds the user to the database.

    PHP code

    You also need to create a script to log the user out of the system. It terminates the session for the user with the given unique ID and name, and then redirects the user to the login page.

    PHP code

    Finally, the "auth.php" script can be used to make pages accessible only to authorized users. It checks the login details and, if they are correct, allows the user to browse the pages, and if not, asks them to log in. In addition, if someone tries to hack the site by creating one of the sessions, it will be interrupted, as in the general case.

    PHP code

    One of the conditions in the code above is the subject of the question in .

    The following code needs to be inserted into the page for authorized users, it is called, for example, “member.php”, but yours can be called anything you like.

    PHP code

    You are authorized to access this page. Go out ( )

    User authentication is ready!

    Last modified on April 5th, 2018 by Vincy.

    User login and registration is a basic requirement for any CMS applications. This is the initial work while starting a project. Application with user login authentication provides security by preventing anonymous access. There are various ways to enable authentication in our application like by enabling OAuth login or by implementing Single Sign-on (SSO) and similar other ways. In a previous tutorial, we have seen how to implement and also about.

    This example includes both login and the registration functionalities. I have used MySQL database to store the registered members. The user registration will contain input to get the details from the user. On submitting this form, the form data are posted to PHP and stored in the database. User password will be encrypted before storing into the database. before posting to the PHP code. When the user is logged in with the valid credentials, then the user and he will be allowed to proceed further.

    User Registration Form

    This code is to show the signup form to the user. When the user submits the form with his details, the JavaScript function will be called to validate user input. After successful validation, the PHP code will read the posted form data to execute database insert.