Menu
Is free
check in
the main  /  Installation and configuration/ Jquery registration and login forms. Step-by-step registration with jQuery

Jquery registration and authorization forms. Step-by-step registration with jQuery

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 both for the forum and for the online store and for social networks (such as, for example, 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 it. Nothing will work without it.

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 this article, I explain in detail how to do this.

And so, we have a Database (abbreviated as a database), 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 define what fields it will contain. These fields will correspond to the fields from the registration form.

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

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

All fields of type “VARCHAR” must have a default value of NULL.


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

Everything, 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 PHP MySQLi extension.

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

DB connection error... Error description: ".mysqli_connect_error ()."

"; exit ();) // Set the connection encoding $ mysqli-> set_charset (" utf8 "); // For convenience, let's 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 hooked up to form handlers.

Pay attention to the variable $ address_site, here I indicated the name of my test site that I will be working on. You should indicate the name of your site accordingly.

Site structure

Now let's take a 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 (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, check in and authorization, add to the site header 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:

Name of our site

As a result, the 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.

Go to the Database (in phpMyAdmin), open the table structure users and see what fields we need. This means that we need fields for entering the 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 field for entering 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 the 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 for the sake of interest he enters the registration page directly by writing to the address bar of the browser site_address / form_register.php, then in this case, instead of the registration form, we will display a title to him stating that he has already been registered.

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

You are already registered

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


Via required attribute, we have made all fields required.

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


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

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

The code is well commented out, so I will focus on just one point.

Inside the 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 it 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.

Checking email for validity with 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 have set the type email (type = "email"), this warns us a little 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 from email on the text and that's it, our check will no longer be valid.


And in that case, we need to make a more reliable check. For 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, add the email validation check code. Here we add a code for checking the length of the entered password. Its length must be at least 6 characters.

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

And so, we are done with validating the form on the client side. Now we can send it to the server, where we will also make a couple of checks and add the 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 sending method is specified in the attribute value method.

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

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

Therefore, we need to check for the presence of a cell in the global POST array, the name of which matches the name of our "Register" button from the form. Thus, we check whether the "Register" button was clicked or not.

If an attacker tries to go directly to this file, he 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.

Error! home page.

"); } ?>

The value of the captcha 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 specified " // (1) Place for the next piece of code"we write:

// Check the resulting captcha // Trim the spaces from the beginning and from the 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 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 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 home 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, if there are cells with the names corresponding to 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 line from this cell, otherwise, we redirect the user back to the page with the registration form.

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

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

/ * Check if the global array $ _POST contains the data sent from the form and enclose the submitted data in ordinary variables. * / If (isset ($ _ POST ["first_name"])) (// Trim the spaces from the beginning and from the 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

Missing name field

"; // 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 security , 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"]. = "

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) Place of the code 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 paprol $ 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 have to check the format of the received postal address and its uniqueness in the database. That is, is there any user already registered with the same mailing address?

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 ();) // We check if there is already such an address in the database. $ Result_query = $ mysqli-> query ("SELECT` email` FROM `users` WHERE` email` = "". $ Email. "" "); // If the number of received rows are exactly one, so a 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"]. = "

A user with this mailing 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 the 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 ();) / * 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:

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

Failed to add a user to the database request

"; // 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 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 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 act on fields from this form as well.

The session is also started in the file header.php, so in the file form_auth.php you do not need to start the session, because we will get an error.


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

After eliminating 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 auth.php, this means that the form will be processed in this file.

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

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

/ * Check if the form was submitted, that is, if the Login button was clicked. If yes, then go ahead, if not, then 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) Space for the next piece of code) else (exit ("

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

"); }

// Check the resulting captcha if (isset ($ _ POST ["captcha"])) (// Trim the spaces from the beginning and end of the line $ 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 not correct , 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 home page.

"); }

If the user entered the verification code correctly, then go ahead, otherwise we return it to the authorization page.

Checking the postal address

// Trim the spaces from the beginning and end of the line $ 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 incorrect 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"]. = "

Email field is missing

"; // 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) Space for processing the password

If the user entered a postal address in an incorrect format or the value of the postal address field is empty, then we return it to the authorization page where we display a message about it.

Password check

The next field to be processed is the password field. To the specified location " // (3) Place to process the password", we write:

If (isset ($ _ POST ["password"])) (// Trim the 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 the passwords are in the encrypted form in the database. An 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 sample of a user whose mail address is equal to the received mail address and the password is equal to the received password.

// Query in 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"]. = "

Request error on user fetch 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 ( // We check if there is no user with such data in the database, then we display an error message if ($ result_query_select-> num_rows == 1) (// If the entered data match the data from the database, then we 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"]. = "

Incorrect 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 ();))

Log out from the site

And the last thing we do is procedure for leaving the site... At the moment, in the header, we display links to the authorization page and to 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 Output.

Modified piece of code from file header.php:

check in

Output

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

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 the 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 the procedure for leaving the site.

All scripts are tested and working. You can download the archive with the files of this small site at 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, also, if you notice any error in the article, please let me know about it.

Lesson plan (Part 5):

  1. Create HTML structure for the login form
  2. We process the received data
  3. We display the user's greeting in the site header

Did you like the article?

If you need to make one of the sections of your site available to a limited but indefinite circle of people, the easiest way to do this is by registering and authorizing users. There are many ways to authorize users. Both web server tools and programming language tools can be used. We'll talk about the case where PHP sessions are used.

You probably would like to see a more modern way of creating such a shape. I still have a complete modern and up-to-date presentation, but you can see that the feedback form can be built using object-oriented techniques in PHP.

First, let's discuss all the steps that we will take next. What do we even need? We need a script that will register a user, authorize a user, redirect the user somewhere after authorization. We will also need to create a page that will be protected from access by unauthorized users. For registration and authorization, we will need to create HTML forms. We will store information about registered users in a database. This means that we still need a script to connect to the DBMS. All our work will be performed by functions that we ourselves will write. We will save these functions in a separate file.

So, we need the following files:

  • connection with DBMS;
  • custom functions;
  • authorization;
  • check in;
  • protected page;
  • user shutdown script;
  • a script that checks the user's authorization status;
  • style sheet for the simplest design of our pages.

All of this will be pointless if you don't have a corresponding table in your database. Launch your DBMS management tool (PhpMyAdmin or command line, whichever is more convenient) and run the following query in it:

CREATE TABLE `users` (` id` int (11) NOT NULL AUTO_INCREMENT, `login` char (16) NOT NULL,` password` char (40) NOT NULL, `reg_date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (` id`)) ENGINE = MyISAM DEFAULT CHARSET = utf8 AUTO_INCREMENT = 1;

I will name our script files like this (they will all be in the same directory):

  • database.php;
  • functions.php;
  • login.php;
  • registration.php;
  • index.php;
  • logout.php;
  • checkAuth.php;
  • style.css.

The purpose of each of them, I am sure, is clear to you. Let's start with the DBMS connection script. You've seen it before. Just save the code for this script in a file called database.php. We will declare custom functions in the functions.php file. How will this all work? An unauthorized user tries to access the protected document index.php, the system checks if the user is authorized, if the user is not authorized, he is redirected to the authorization page. On the authorization page, the user should see an authorization form. Let's do it.

User authorization

register.

Now we need to give our shape a certain look. At the same time, we will define the rules for other elements. I'm going to give you the full content of the stylesheet, getting ahead of myself.

/ * style.css file * / .row (margin-bottom: 10px; width: 220px;) .row label (display: block; font-weight: bold;) .row input.text (font-size: 1.2em; padding: 2px 5px;) .to_reg (font-size: 0.9em;). instruction (font-size: 0.8em; color: #aaaaaa; margin-left: 2px; cursor: default;) .error (color: red; margin-left: 3px;)

If everything is done correctly, you should have the following in your browser:

Of course, we do not have a single registered user yet, and in order to log in, you need to register. Let's make a registration form.

User registration

" />

You've probably noticed that there are PHP variables in the HTML code. They are the content of the attributes of the text fields of the forms, the content of the containers intended for displaying errors. But we have not initialized these variables. Let's do that.

User registration

" />
The username can contain only Latin characters, numbers, symbols "_", "-", ".". Username length must be at least 4 characters and no longer than 16 characters
In the password, you can use only Latin characters, numbers, symbols "_", "!", "(", ")". Password must be at least 6 characters and no longer than 16 characters
Repeat the previously entered password

There is no parameter specified in the action attribute of the form tag. In this case, when the form data is submitted, it will be processed in the same script from which it was submitted. So we need to write the code that processes the form data. But let's first discuss the algorithm for their processing.

We need the login and password fields not to be empty. Then you need to check the login for compliance with the requirements. The password must also meet the described requirements, and the re-entered password must match it and, moreover, they must be identical. If any of these conditions are not met, the processing of the form data should be stopped, the corresponding notification should be written to the array of error messages, and it should be displayed to the user. For the convenience of the user, we will save the login entered by him (if he specified it), writing its value to the $ fields array.

If everything is fine, in your browser window, referring to the registration.php document, you should see something like this:

Now, let's say the user clicks on the registration button without filling out the form fields. According to our algorithm, login and password cannot be empty. If this condition is not met, registration is not possible. We keep in mind that the processing of the form data takes place in the current script. So we need to change its code by adding the appropriate checks. We will immediately stipulate the following checks. If both login and password are entered, you need to check their compliance with the specified requirements. To check the login and password, we will create custom functions in the functions.php file.

/ ** * functions.php * File with custom functions * / // Include a file with parameters for connecting to the DBMS require_once ("database.php"); // Checking the username function checkLogin ($ str) (// Initialize the variable with a possible error message $ error = ""; // If there is no login string, return the error message if (! $ Str) ($ error = " You did not enter a username "; return $ error;) / ** * Check the username using regular expressions * Login must be at least 4, no longer than 16 characters * It must contain Latin characters, numbers, * it can be symbols "_", "-", "." * / $ pattern = "/^ [-_.az\d ](4,16)$/i"; $ result = preg_match ($ pattern, $ str) ; // If the check fails, return an error message if (! $ Result) ($ error = "Invalid characters in the username or the username is too short (long)"; return $ error;) // If everything is fine, return true return true;) // Check the user's password function checkPassword ($ str) (// Initialize the variable with a possible error message $ error = ""; // If there is no a string with a login appears, return an error message if (! $ str) ($ error = "You did not enter a password"; return $ error; ) / ** * Check the user's password using regular expressions * Password must be no shorter than 6, no longer than 16 characters * It must contain Latin characters, numbers, * it can contain symbols "_", "!", " (",") "* / $ pattern =" /^ [_!)(.az\d"(6,16)$/i "; $ result = preg_match ($ pattern, $ str); // If the check failed, return an error message if (! $ result) ($ error = "Invalid characters in the user password or the password is too short (long)"; return $ error;) // If everything is fine, return true return true; )

Now we need to modify the registration.php file to use the functions we have declared. We will add a condition to the script to check that the registration button is clicked. Inside this condition, a login and password check is started. If any of the checks fails, we re-render the form and display an error message. If there are no errors, we register the user, we no longer display the registration form, inform the user about successful registration, and using the header () function redirect him to the authorization form.

You have successfully registered in the system. You will now be redirected to the login page. If this did not happen, go to it using a direct link.

"; header (" Refresh: 5; URL = login.php ");) // Otherwise inform the user about the error else ($ errors [" full_error "] = $ reg;)))?> User registration
" />
The username can contain only Latin characters, numbers, symbols "_", "-", ".". Username length must be at least 4 characters and no longer than 16 characters
In the password, you can use only Latin characters, numbers, symbols "_", "!", "(", ")". Password must be at least 6 characters and no longer than 16 characters
Repeat the previously entered password

You should have noticed another new function in the script - registration (). And we have not announced it yet. Let's do that.

// User registration function function registration ($ login, $ password) (// Initialize a variable with a possible error message $ error = ""; // If there is no login string, return an error message if (! $ Login) ($ error = "Login not specified"; return $ error;) elseif (! $ password) ($ error = "Password not specified"; return $ error;) // Check if the user is already registered // Connect to the DBMS connect () ; // Write a query string $ sql = "SELECT` id` FROM `users` WHERE` login` = "". $ Login. "" "; // Make a query to the database $ query = mysql_query ($ sql) or die ( ""); // Look at the number of users with this login, if there is at least one, // return an error message if (mysql_num_rows ($ query)> 0) ($ error = "The user with the specified login is already registered"; return $ error;) // If there is no such user, register it // Write a query string $ sql = "INSERT INTO` users` (`id`,` login`, `password`) VALUES (NULL," ". $ login." "," ". $ password. "") "; // Make a query to the database $ query = mysql_query ($ sql) or die ("

Unable to add user: ". Mysql_error ().". An error occurred at the line ". __LINE__."

"); // Do not forget to disconnect from the DBMS mysql_close (); // Return the value true, indicating the successful registration of the user return true;)

If everything is ok, your user will be registered. You can test the form. Try to register users with the same logins. After successful registration, the user will be redirected to the authorization form. Previously, we just created the markup to display this form. Since there is no parameter specified in its action attribute, the data submitted by the form will be processed in the same script. So we need to write the code for processing, and add it to the login.php document.

User authorization

;">

If you are not registered in the system, register.

You've probably noticed that in the authorization script we have another unfamiliar function - authorization (). This function should authorize the user by first checking if there is a registered user in the database with the same username and password. If such a user is not found, the authorization will be interrupted and a failure message will be displayed on the screen. If the check is successful, the authorization () function will start a session and write the username and password values ​​to it, inform the script about the authorization success, and the script will redirect the user to the protected resource page.

/ ** * User authorization function. * Authorization of users with us will be carried out * using PHP sessions. * / function authorization ($ login, $ password) (// Initialize a variable with a possible error message $ error = ""; // If there is no login line, return an error message if (! $ login) ($ error = " Login not specified "; return $ error;) elseif (! $ Password) ($ error =" Password not specified "; return $ error;) // Check if the user is already registered // Connect to the DBMS connect (); // We need to check if there is such a user among the registered ones // Composing a query string $ sql = "SELECT` id` FROM `users` WHERE` login` = "". $ Login. "" AND `password` =" ". $ Password . "" "; // Run the query $ query = mysql_query ($ sql) or die ("

Unable to execute query: ". Mysql_error ().". An error occurred at the line ". __LINE__."

"); // If there is no user with such data, return an error message if (mysql_num_rows ($ query) == 0) ($ error =" The user with the specified data is not registered "; return $ error;) // If the user exists , start the session session_start (); // And write the username and password into it // For this we use the superglobal array $ _SESSION $ _SESSION ["login"] = $ login; $ _SESSION ["password"] = $ password; / / Do not forget to close the database connection mysql_close (); // Return true for the message about successful user authorization return true;)

When a user enters a protected page, you should check the correctness of his authorization data. For this we need one more custom function. Let's call it checkAuth (). Its task will be to reconcile the user's authorization data with those that are stored in our database. If the data does not match, the user will be redirected to the authorization page.

Function checkAuth ($ login, $ password) (// If there is no username or password, return false if (! $ Login ||! $ Password) return false; // Check if such a user is registered // Connect to the DBMS connect (); // Create a query string $ sql = "SELECT` id` FROM `users` WHERE` login` = "". $ Login. "" AND `password` =" ". $ Password." ""; // Execute the query $ query = mysql_query ($ sql) or die ("

Unable to execute query: ". Mysql_error ().". An error occurred at the line ". __LINE__."

"); // If there is no user with such data, return false; if (mysql_num_rows ($ query) == 0) (return false;) // Do not forget to close the database connection mysql_close (); // Otherwise, return true return true;)

Now that the user is on the secure page, we need to call the function to check the authorization data. We will place the call and check script in a separate checkAuth.php file and connect it to the pages that will be closed for public access.

/ ** * Script for checking user authorization * / // We start a session from which we will extract the login and password // of logged in users session_start (); // Include a file with custom functions require_once ("functions.php"); / ** * To determine if a user is logged in, we need to * check if there are records in the database for his login * and password. To do this, we will use the custom function * to check the correctness of the logged in user data. * If this function returns false, then there is no authorization. * In the absence of authorization, we simply redirect * the user to the authorization page. * / // If the session contains both login and password data, // check them if (isset ($ _ SESSION ["login"]) && $ _SESSION ["login"] && isset ($ _ SESSION ["password" ]) && $ _SESSION ["password"]) (// If validation of existing data fails if (! CheckAuth ($ _ SESSION ["login"], $ _SESSION ["password"])) (// Redirect the user to the authorization page header ("location: login.php"); // Stop executing the script exit;)) // If there is no data either about the login or the user's password, // consider that there is no authorization, redirect the user // to the authorization page else ( header ("location: login.php"); // Abort the script exit;)

Now let's create the code for our secure page. It will be pretty simple.

User authorization and registration

Successful authorization.

You have accessed a secure page. You can log out of the system.

As you can see, we include only one file in the secure document - checkAuth.php. All other files are included in other scripts. Therefore, our code does not look cumbersome. We have organized the registration and authorization of users. Now you need to allow users to log out. To do this, we will create a script in the logout.php file.

/ ** * User logout script. Since users are * authorized through sessions, their username and password are stored * in the $ _SESSION superglobal array. To log out *, simply destroy the values ​​* of the $ _SESSION ["login"] and $ _SESSION ["password"] array, after * which we redirect the user to the authorization page * / // Be sure to start the session session_start (); unset ($ _ SESSION ["login"]); unset ($ _ SESSION ["password"]); header ("location: login.php");

The script for registration, authorization and user verification is ready. You can use it at home, supplement it, change it to suit your needs. If you have any questions, you can ask them in the comments. You can download yourself all the files mentioned here, packed into one archive.

P.S. I am aware that it is better to write object-oriented code, I know that it is not worth transmitting and storing the password in clear text, that the information entered into the database must be checked beforehand. I know. I will not talk about this here.

Everything happens under PHP control, and the data is stored in a MySQL database.

The system uses an excellent slide-out panel developed by Web-kreation.

Step 1 - MySQL

First, we need to create a table that will contain all the data about registered users. The request code is available in the file table.sql in the source archive.

table.sql

--
- The structure of the `tz_members` table
--
CREATE TABLE `tz_members` (
`id` int (11) NOT NULL auto_increment,
`usr` varchar (32) collate utf8_unicode_ci NOT NULL default" ",
`pass` varchar (32) collate utf8_unicode_ci NOT NULL default" ",
`email` varchar (255) collate utf8_unicode_ci NOT NULL default" ",
`regIP` varchar (15) collate utf8_unicode_ci NOT NULL default" ",
`dt` datetime NOT NULL default" 0000-00-00 00:00:00 ",
PRIMARY KEY (`id`),
UNIQUE KEY `usr` (` usr`)
) ENGINE = MyISAM DEFAULT CHARSET = utf8 COLLATE = utf8_unicode_ci;

We define id as an integer with an option auto_increment- it will be automatically assigned for every new registered user. Also usr defined as unique key- the table does not allow the existence of two records with the same username.

Later, we will use the specified properties during the registration process when the username is entered.

After creating the table, you need to fill in the variables for connecting to your database in the file connect.php so that the code can run on your server.

Step 2 - XHTML

First, we need to embed the Web-creation form in our page.

demo.php






JQuery slide-out bar


Solution for registering / logging users into the site



if (! $ _ SESSION ["id"]):
// If you are not registered yet
?>



Login for registered users


if ($ _ SESSION ["msg"] ["login-err"])
{
echo "
". $ _ SESSION [" msg "] [" login-err "]."
";
unset ($ _ SESSION ["msg"] ["login-err"]);
// This will output login errors, if any
}
?>












Not registered yet? Enter your data!


if ($ _ SESSION ["msg"] ["reg-err"])
{
echo "
". $ _ SESSION [" msg "] [" reg-err "]."
";
unset ($ _ SESSION ["msg"] ["reg-err"]);
// Here we display the registration error, if any
}
if ($ _ SESSION ["msg"] ["reg-success"])
{
echo "
". $ _ SESSION [" msg "] [" reg-success "]."
";
unset ($ _ SESSION ["msg"] ["reg-success"]);
// Here we display a message about successful registration
}
?>








else:
// If you are logged in
?>

For registered users


Sample data


Go to user page

Log out



endif;
// Close the IF-ELSE construction
?>






There are PHP statements in several places in the code that check whether $ _SESSION ["usr"] or $ _SESSION ["id"]... They are only true if the visitor to the page is a registered user, which allows us to show hidden content to registered visitors.

After the form, we place the rest of the page content.




JQuery slide-out bar


Simple registration management using PHP and jQuery




Some text ...




There is nothing special about the code.

Step 3 - PHP

Now we will convert the form into a complete registration and login system. In order to solve the problem, you will need something besides the usual PHP code. All code is split into two parts.

If you plan to add anything, it is best to split everything into several separate files and include them as needed. This approach helps you develop large projects and still reuse code in different parts of the site.

This is how it is implemented here.

demo.php

define ("INCLUDE_CHECK", true);
require "connect.php";
require "functions.php";
// These two files can only be included if INCLUDE_CHECK is defined
session_name ("tzLogin");
// Start session
session_set_cookie_params (2 * 7 * 24 * 60 * 60);
// Defines the cookie lifetime for two weeks
session_start ();
if ($ _ SESSION ["id"] &&! isset ($ _ COOKIE ["tzRemember"]) &&! $ _ SESSION ["rememberMe"])
{
// If you are logged in, but you do not have cookies tzRemember (restart browser)
// and you have not checked the checkbox Remember me:
$ _SESSION = array ();
session_destroy ();
// Delete the session
}
if (isset ($ _ GET ["logoff"]))
{
$ _SESSION = array ();
session_destroy ();
header ("Location: demo.php");
exit;
}
if ($ _ POST ["submit"] == "Login")
{
// Check that the request came from the Login form
$ err = array ();
// Save the error
if (! $ _ POST ["username"] ||! $ _ POST ["password"])
$ err = "All fields must be filled!";
if (! count ($ err))
{

$ _POST ["password"] = mysql_real_escape_string ($ _ POST ["password"]);
$ _POST ["rememberMe"] = (int) $ _ POST ["rememberMe"];
// Prepare all data
$ row = mysql_fetch_assoc (mysql_query ("SELECT id, usr FROM tz_members WHERE usr =" ($ _ POST ["username"]) "AND pass =" ". md5 ($ _ POST [" password "])." "")) ;
if ($ row ["usr"])
{
// If everything is ok, then log in
$ _SESSION ["usr"] = $ row ["usr"];
$ _SESSION ["id"] = $ row ["id"];
$ _SESSION ["rememberMe"] = $ _POST ["rememberMe"];
// Save some data in the session
setcookie ("tzRemember", $ _ POST ["rememberMe"]);
// Create cookies tzRemember
}
else $ err = "Wrong username or / and password!";
}
if ($ err)
$ _SESSION ["msg"] ["login-err"] = implode ("
", $ err);
// Save the error message in the session
header ("Location: demo.php");
exit;
}

Here cookies tzRemember acts as a control element for determining that it is necessary to provide a logout for a user who has not checked the "Remember me" checkbox. If there is no cookie (due to browser restart) and the visitor has not checked the "remember me" option, we delete the session.

The session itself will remain active for two weeks (as set in the parameter session_set_cookie_params).

And here is the second part demo.php.

Else if ($ _ POST ["submit"] == "Register")
{
// If the request is sent from the Registration form
$ err = array ();
if (strlen ($ _ POST ["username"])<4 || strlen($_POST["username"])>32)
{
$ err = "Username must be between 3 and 32 characters long!";
}
if (preg_match ("/ [^ a-z0-9 \ - \ _ \.] + / i", $ _ POST ["username"]))
{
$ err = "Username contains invalid characters!";
}
if (! checkEmail ($ _ POST ["email"]))
{
$ err = "Your email address is incorrect!";
}
if (! count ($ err))
{
// If there are no errors
$ pass = substr (md5 ($ _ SERVER ["REMOTE_ADDR"]. microtime (). rand (1,100000)), 0.6);
// Generate a random password
$ _POST ["email"] = mysql_real_escape_string ($ _ POST ["email"]);
$ _POST ["username"] = mysql_real_escape_string ($ _ POST ["username"]);
// prepare the data
mysql_query ("INSERT INTO tz_members (usr, pass, email, regIP, dt)
VALUES (
"". $ _ POST ["username"]. "",
"" .md5 ($ pass). "",
"". $ _ POST ["email"]. "",
"". $ _ SERVER ["REMOTE_ADDR"]. "",
NOW ()
)");
if (mysql_affected_rows ($ link) == 1)
{
send_mail (" [email protected] website",
$ _POST ["email"],
"Demonstration of the registration system - password generation",
"Your password:". $ Pass);
$ _SESSION ["msg"] ["reg-success"] = "We sent you an email with your new password!";
}
else $ err = "This username is already in use!";
}
if (count ($ err))
{
$ _SESSION ["msg"] ["reg-err"] = implode ("
", $ err);
}
header ("Location: demo.php");
exit;
}
$ script = "";
if ($ _ SESSION ["msg"])
{
// The script shows a pop-up bar on the loading page
$ script = "
";
}

Store all defined errors in an array $ err which is later assigned to a variable $ _SESSION... Thus, access to it is preserved after browser redirection.

Some sites may receive a warning when a form is submitted or the next time the page is refreshed that the data has already been submitted. This can be a problem as it leads to duplicate registrations and unnecessary load on the server.

We use the header function to prevent the error by redirecting the browser to the same page. This updates the page view without the browser recognizing it as a form request. As a result, the page is refreshed and no data is sent.

But since we use $ _SESSION to store all errors found, it is very important that we reset all variables as soon as the error is shown to the user. Otherwise, it will be displayed on every page view.

An additional script is also used that displays a panel on the download page so that the message is visible to the user.


Step 4 - CSS

The slide-out panel uses its own style file. Thus, we just have to create a style for our page.

demo.css

body, h1, h2, h3, p, quote, small, form, input, ul, li, ol, label (
/ * Reset rules * /
margin: 0px;
padding: 0px;
}
body (
color: # 555555;
font-size: 13px;
background: #eeeeee;
font-family: Arial, Helvetica, sans-serif;
width: 100%;
}
h1 (
font-size: 28px;
font-weight: bold;
font-family: "Trebuchet MS", Arial, Helvetica, sans-serif;
letter-spacing: 1px;
}
h2 (
font-family: "Arial Narrow", Arial, Helvetica, sans-serif;
font-size: 10px;
font-weight: normal;
letter-spacing: 1px;
padding-left: 2px;
text-transform: uppercase;
white-space: wrap;
margin-top: 4px;
color: # 888888;
}
#main p (
padding-bottom: 8px;
}
.clear (
clear: both;
}
#main (
width: 800px;
/ * Center in the middle of the page * /
margin: 60px auto;
}
.container (
margin-top: 20px;
background: #FFFFFF;
border: 1px solid # E0E0E0;
padding: 15px;
/ * Rounded corners * /
-moz-border-radius: 20px;
-khtml-border-radius: 20px;
-webkit-border-radius: 20px;
border-radius: 20px;
}
.err (
color: red;
}
.success (
color: # 00CC00;
}
a, a: visited (
color: # 00BBFF;
text-decoration: none;
outline: none;
}
a: hover (
text-decoration: underline;
}
.tutorial-info (
text-align: center;
padding: 10px;
}

Step 5 - jQuery

The slide bar has its own jQuery.

demo.php








The first line includes the jQuery library from the Google CDN. This is followed by an IE6 PNG patch for transparency elements. Then the panel script is included

The $ script variable shows a panel on the download page when needed.

In this article, we'll walk you through the step-by-step registration using jQuery.

If registration on your site involves filling in several dozen fields, it is not very rational to place them on one page. After all, the user is a very lazy creature and does not want to fill in after seeing all these fields.

An alternative option is to split the registration into several steps. This generates a lot of positive feedback at once - after all, starting to perform the steps, the user most often has a desire to complete their implementation.

It is also logical to split the registration into logical blocks - contact information, address, personal data, and so on.

For step-by-step registration, there is absolutely no reason to create several forms and send data to the server separately. It is much more convenient to put everything in one form, but show the user only a certain part of the form at each step. This is exactly what the logic will be in our example.

In addition to logic, it should be borne in mind that at first only the link is visible "Forward"/"The next step", but at the last step it is not visible, but visible "Back" and "Check in".

Let's look at the example itself:

Page

Step 1

Login:

Email:

Password:

Step 2

Name:

Surname:

Age:

Step 3

Country:

City:

Street:

Back Next step

body (margin: 0;) / * General styles are over * / form (width: 30%; margin: 0 auto;) form div.step (display: none;) form div.step p.step (text-align: center ; font-size: 28px;) form div.step p () form div.step p input (float: right;) a.back (display: none;) form input (display: none;) a (color: # 006600 ; text-decoration: none;) form p.talign (text-align: center;)

We will place the script responsible for switching steps in js / steps_registration.js, do not forget to also include the jQuery library:

$ (document) .ready (function () (// Wait for the page to load var steps = $ ("form"). children (". step"); // find all the steps of the form $ (steps) .show (); / / show the first step var current_step = 0; // set the current step $ ("a.next"). click (function () (// Event of clicking on the "Next step" link if (current_step == steps.length-2) (// check if the next step will be the last one $ (this) .hide (); // hide the "Next step" link $ ("form input"). show (); // show the "Register" button) $ (" a.back "). show (); // show the" Back "link current_step ++; // increase the counter of the current slide changeStep (current_step); // change the step)); $ (" a.back "). click (function ( ) (// Event of clicking on a small image if (current_step == 1) (// check if the previous step will be the first $ (this) .hide (); // hide the "Back" link) $ ("form input") .hide (); // hide the "Register" button $ ("a.next"). show (); // show the "Next step" link current_step--; // decrease the counter of the current slide changeStep (current_step); // change the step)); function changeStep (i) (// step change function $ (steps) .hide (); // hide all steps $ (steps [i]). show (); // show the current one)));

We will not write the php-sending code here, since this does not quite apply to this lesson. It should only be noted that the letter is sent to the address specified in the first step of the form. In any case, you can download the demo files and see for yourself.