Home Children's dentistry Executive registration php. Simple user registration system

Executive registration php. Simple user registration system

Creating a membership based site seems like a daunting task at first. If you ever wanted to do this by yourself, then just gave up when you started to think how you are going to put it together using your PHP skills, then this article is for you. We are going to walk you through every aspect of creating a membership based site, with a secure members area protected by password.

The whole process consists of two big parts: user registration and user authentication. In the first part, we are going to cover creation of the registration form and storing the data in a MySQL database. In the second part, we will create the login form and use it to allow users access in the secure area.

Download the code

You can download the whole source code for the registration/login system from the link below:

Configuration & Upload
The ReadMe file contains detailed instructions.

Open the source\include\membersite_config.php file in a text editor and update the configuration. (Database login, your website’s name, your email address etc).

Upload the whole directory contents. Test the register.php by submitting the form.

The registration form

In order to create a user account, we need to gather a minimal amount of information from the user. We need his name, his email address and his desired username and password. Of course, we can ask for more information at this point, but a long form is always a turn-off. So let’s limit ourselves to just those fields.

Here is the registration form:

Register

So, we have text fields for name, email and the password. Note that we are using the for better usability.

Form validation

At this point it is a good idea to put some form validation code in place, so we make sure that we have all the data required to create the user account. We need to check if name and email, and password are filled in and that the email is in the proper format.

Handling the form submission

Now we have to handle the form data that is submitted.

Here is the sequence (see the file fg_membersite.php in the downloaded source):

function RegisterUser() ( if(!isset($_POST["submitted"])) ( return false; ) $formvars = array(); if(!$this->ValidateRegistrationSubmission()) ( return false; ) $this- >CollectRegistrationSubmission($formvars); if(!$this->SaveToDatabase($formvars)) ( return false; ) if(!$this->SendUserConfirmationEmail($formvars)) ( return false; ) $this->SendAdminIntimationEmail($ formvars); return true;

First, we validate the form submission. Then we collect and ‘sanitize’ the form submission data (always do this before sending email, saving to database etc). The form submission is then saved to the database table. We send an email to the user requesting confirmation. Then we intimate the admin that a user has registered.

Saving the data in the database

Now that we gathered all the data, we need to store it into the database.
Here is how we save the form submission to the database.

function SaveToDatabase(&$formvars) ( if(!$this->DBLogin()) ( $this->HandleError("Database login failed!"); return false; ) if(!$this->Ensuretable()) ( return false; ) if(!$this->IsFieldUnique($formvars,"email")) ( $this->HandleError("This email is already registered"); return false; ) if(!$this->IsFieldUnique( $formvars,"username")) ( $this->HandleError("This UserName is already used. Please try another username"); return false; ) if(!$this->InsertIntoDB($formvars)) ( $this- >HandleError("Inserting to Database failed!"); return false; return true;

Note that you have configured the Database login details in the membersite_config.php file. Most of the cases, you can use “localhost” for database host.
After logging in, we make sure that the table is existing.(If not, the script will create the required table).
Then we make sure that the username and email are unique. If it is not unique, we return error back to the user.

The database table structure

This is the table structure. The CreateTable() function in the fg_membersite.php file creates the table. Here is the code:

function CreateTable() ( $qry = "Create Table $this->tablename (". "id_user INT NOT NULL AUTO_INCREMENT ," "name VARCHAR(128) NOT NULL ," "email VARCHAR(64) NOT NULL ," " "phone_number VARCHAR(16) NOT NULL ," "username VARCHAR(16) NOT NULL ," "password VARCHAR(32) NOT NULL ," "confirmcode VARCHAR(32) ," " ")"; if(!mysql_query($qry,$this->connection)) ( $this->HandleDBError("Error creating the table \nquery was\n $qry"); return false; ) return true )

The id_user field will contain the unique id of the user, and is also the primary key of the table. Notice that we allow 32 characters for the password field. We do this because, as an added security measure, we will store the password in the database encrypted using MD5. Please note that because MD5 is an one-way encryption method, we won’t be able to recover the password in case the user forgets it.

Inserting the registration to the table

Here is the code that we use to insert data into the database. We will have all our data available in the $formvars array.

function InsertIntoDB(&$formvars) ( $confirmcode = $this->MakeConfirmationMd5($formvars["email"]); $insert_query = "insert into ".$this->tablename."(name, email, username, password, confirmcode) values ​​("" . $this->SanitizeForSQL($formvars["name"]) . "", "" . $this->SanitizeForSQL($formvars["email"]) . "", "" . $ this->SanitizeForSQL($formvars["username"]) . "", "" . md5($formvars["password"]) "", "" . $confirmcode . "")"; if(!mysql_query( $insert_query ,$this->connection)) ( $this->HandleDBError("Error inserting data to the table\nquery:$insert_query"); return false; ) return true )

Notice that we use PHP function md5() to encrypt the password before inserting it into the database.
Also, we make the unique confirmation code from the user’s email address.

Sending emails

Now that we have the registration in our database, we will send a confirmation email to the user. The user has to click a link in the confirmation email to complete the registration process.

function SendUserConfirmationEmail(&$formvars) ( $mailer = new PHPMailer(); $mailer->CharSet = "utf-8"; $mailer->AddAddress($formvars["email"],$formvars["name"]) ; $mailer->Subject = "Your registration with ".$this->sitename; $mailer->From = $this->GetFromAddress(); $confirmcode = urlencode($this->MakeConfirmationMd5($formvars["email" ])); $confirm_url = $this->GetAbsoluteURLFolder()."/confirmreg.php?code=".$confirmcode; $mailer->Body ="Hello ".$formvars["name"]."\r\ n\r\n". "Thanks for your registration with ".$this->sitename."\r\n". "Please click the link below to confirm your registration.\r\n." "$confirm_url\r \n". "\r\n". "Regards,\r\n". "Webmaster\r\n". $this->sitename; if(!$mailer->Send()) ( $this-> HandleError("Failed sending registration confirmation email."); return false; return true)

Updates

9th Jan 2012
Reset Password/Change Password features are added
The code is now shared at GitHub.

Welcome backUserFullName(); ?>!

License


The code is shared under LGPL license. You can freely use it on commercial or non-commercial websites.

No related posts.

Comments on this entry are closed.

In order to divide site visitors into certain groups, a small system must be installed on the site registration in php. In this way, you conditionally divide visitors into two groups of simply random visitors and into a more privileged group of users to whom you provide more valuable information.

In most cases, a more simplified registration system is used, which is written in php in one file register.php.

So, we've digressed a bit, and now we'll take a closer look at the registration file.

Register.php file

To ensure that this does not take up a lot of your time, we will create a system that will collect users, accepting minimal contact information from them. IN in this case We will enter everything into the mysql database. For the highest speed of the database, we will create the users table in the MyISAM format and in utf-8 encoding.

Note! All scripts must always be written in the same encoding. All site files and the MySql database must be in the same encoding. The most common encodings are UTF-8 and Windows-1251.

Why you need to write everything in one encoding we will talk about later. For now, take this information as a strict rule for creating scripts, otherwise you will have problems with scripts in the future. It’s okay, of course, but you’ll just lose a lot of time searching for errors in the script.

How will the script itself work?

We want to simplify everything and get quick results. Therefore, we will receive only login, email and password from users. And to protect against spam robots, we will install a small captcha. Otherwise, some boy from London will write a small robot parser that will fill the entire database with fake users in a few minutes, and will rejoice at his genius and impunity.

Here is the script itself. Everything is recorded in one file register.php:

! `; // red question mark $sha=$sh."scripts/pro/"; //path to the main folder $bg=` bgcolor="#E1FFEB"`; // background color of rows?> Example registration script register.php style.css" />

In this case, the script refers to itself. And it is a form and a processor of data entered into the form. Please note that the file is compressed as a zip archive and contains a configuration file config.php, a users database dump, a file containing auxiliary functions functions.php, a style file style.css and the register.php file itself. There are also several files that are responsible for the operation and generation of captcha symbols.

Hello! Now we will try to implement the simplest registration on the site with using PHP+ MySQL. To do this, Apache must be installed on your computer. The working principle of our script is shown below.

1. Let's start by creating the users table in the database. It will contain user data (login and password). Let's go to phpmyadmin (if you are creating a database on your PC http://localhost/phpmyadmin/). Create a table users, it will have 3 fields.

I create it in the mysql database, you can create it in another database. Next, set the values ​​as in the figure:

2. A connection to this table is required. Let's create a file bd.php. Its content:

$db = mysql_connect("your MySQL server","login for this server","password for this server");
mysql_select_db ("name of the database we are connecting to", $db);
?>

In my case it looks like this:

$db = mysql_connect("localhost","user","1234");
mysql_select_db("mysql",$db);
?>

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 content (all comments inside):



Registration


Registration


















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



{
}
//if the login and password are entered, then we process them so that tags and scripts do not work, you never know what people might enter


//remove extra spaces
$login = trim($login);
$password = trim($password);
// connect to the database
// check for the existence of a user with the same login
$result = mysql_query("SELECT id FROM users WHERE login="$login"",$db);
if (!empty($myrow["id"])) (
exit("Sorry, the login you entered is already registered. Please enter another login.");
}
// if this is not the case, then save the data
$result2 = mysql_query("INSERT INTO users (login,password) VALUES("$login","$password")");
// Check if there are errors
if ($result2=="TRUE")
{
echo "You have successfully registered! Now you can enter the site. Home page";
}
else(
echo "Error! You are not registered.";
}
?>

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) :

// the whole procedure works in sessions. It is where the user's data is stored while he is on the site. It is very important to launch them at the very beginning of the page!!!
session_start();
?>


Home page


Home page











Register



// Check if the login and user id variables are empty
if (empty($_SESSION["login"]) or empty($_SESSION["id"]))
{
// If empty, then we do not display the link
echo "You are logged in as a guest
This link is only available to registered users";
}
else
{

In file index.php We will display a link that will be open only to registered users. This is the whole point of the script - to limit access to any data.

6. There remains a file with verification of the entered login and password. testreg.php (comments inside):

session_start();// the whole procedure works on sessions. It is where the user's data is stored while he is on the site. It is very important to launch them at the very beginning of the page!!!
if (isset($_POST["login"])) ( $login = $_POST["login"]; if ($login == "") ( unset($login);) ) //enter the login entered by the user into $login variable, if it is empty, then destroy the variable
if (isset($_POST["password"])) ( $password=$_POST["password"]; if ($password =="") ( unset($password);) )
//put the password entered by the user into the $password variable, if it is empty, then destroy the variable
if (empty($login) or empty($password)) //if the user has not entered a login or password, then we issue an error and stop the script
{
exit("You have not entered all the information, go back and fill out all the fields!");
}
//if the login and password are entered, then we process them so that tags and scripts do not work, you never know what people might enter
$login = stripslashes($login);
$login = htmlspecialchars($login);
$password = stripslashes($password);
$password = htmlspecialchars($password);
//remove extra spaces
$login = trim($login);
$password = trim($password);
// connect to the database
include("bd.php");// the bd.php file must be in the same folder as all the others, if it is not then just change the path

$result = mysql_query("SELECT * FROM users WHERE login="$login"",$db); //retrieve from the database all data about the user with the entered login
$myrow = mysql_fetch_array($result);
if (empty($myrow["password"]))
{
//if the user with the entered login does not exist
}
else(
//if exists, then check the passwords
if ($myrow["password"]==$password) (
//if the passwords match, then we launch a session for the user! You can congratulate him, he got in!
$_SESSION["login"]=$myrow["login"];
$_SESSION["id"]=$myrow["id"];//this data is used very often, so the logged in user will “carry it with him”
echo "You have successfully entered the site! Home page";
}
else(
//if the passwords do not match

Exit ("Sorry, the login or password you entered is incorrect.");
}
}
?>

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 protection, design, data fields, loading avatars, logging out of your account (to do this, simply destroy variables from the session with the function unset) and so on. Good luck!

I checked everything, it works properly!

Today we will look at the exploitation of a critical 1-day vulnerability in the popular CMS Joomla, which exploded on the Internet at the end of October. It's about about vulnerabilities with numbers CVE-2016-8869, CVE-2016-8870 And CVE-2016-9081. All three come from one piece of code that languished in the depths of the framework for five long years, waiting in the wings, only to then break free and bring with it chaos, hacked sites and the tears of innocent users of this Joomla. Only the most valiant and courageous developers, whose eyes are red from the light of the monitors, and whose keyboards are littered with bread crumbs, were able to challenge the raging evil spirits and lay their heads on the altar of fixes.

WARNING

All information is provided for informational purposes only. Neither the editors nor the author are responsible for any possible harm caused by the materials of this article.

Where it all started

On October 6, 2016, Demis Palma created a topic on Stack Exchange in which he asked: why, in fact, in Joomla version 3.6 there are two methods for registering users with the same name register()? The first one is in the UsersControllerRegistration controller and the second one is in the UsersControllerUser controller. Damis wanted to know if the UsersControllerUser::register() method was used somewhere, or if it was just an evolutionary anachronism left over from the old logic. His concern was that even if this method is not used by any view, it can be called by a crafted query. To which I received a response from a developer under the nickname itoctopus, who confirmed: the problem really exists. And sent a report to the Joomla developers.

Then events developed most rapidly. On October 18, Joomla developers accepted the report from Damis, who by that time had drafted a PoC that would allow user registration. He published a note on his website, where in general outline talked about the problem he found and his thoughts on this matter. Coming out on the same day a new version Joomla 3.6.3, which still contains vulnerable code.

After this, Davide Tampellini spins the bug until it is not registered simple user, and the administrator. And on October 21, a new case arrives to the Joomla security team. It already talks about increasing privileges. On the same day, an announcement appears on the Joomla website that on Tuesday, October 25, the next version with serial number 3.6.3 will be released, which corrects a critical vulnerability in the system kernel.

October 25 Joomla Security Strike Team finds the latest problem created by the piece of code discovered by Damis. Then a commit dated October 21 with the inconspicuous name Prepare 3.6.4 Stable Release is pushed into the main branch of the official Joomla repository, which fixes the unfortunate bug.

After this coming out, numerous interested individuals join the developer community - they begin to promote the vulnerability and prepare exploits.

On October 27, researcher Harry Roberts uploads a ready-made exploit to the Xiphos Research repository that can upload a PHP file to a server with a vulnerable CMS.

Details

Well, the background is over, let's move on to the most interesting part - analysis of the vulnerability. I installed Joomla 3.6.3 as a test version, so all line numbers will be relevant for this version. And all the paths to the files that you will see below will be indicated relative to the root of the installed CMS.

Thanks to Damis Palma's discovery, we know that there are two methods that perform user registration in the system. The first one is used by the CMS and is located in the file /components/com_users/controllers/registration.php:108. The second one (the one we will need to call) lives in /components/com_users/controllers/user.php:293. Let's take a closer look at it.

286: /** 287: * Method to register a user. 288: * 289: * @return boolean 290: * 291: * @since 1.6 292: */ 293: public function register() 294: ( 295: JSession::checkToken("post") or jexit(JText::_ ("JINVALID_TOKEN")); ... 300: // Get the form data. 301: $data = $this->input->post->get("user", array(), "array"); .. 315: $return = $model->validate($form, $data); 316: 317: // Check for errors. 318: if ($return === false) 319: ( ... 345: / / Finish the registration. 346: $return = $model->register($data);

Here I left only interesting lines. The full version of the vulnerable method can be viewed in the Joomla repository.

Let's figure out what happens during normal user registration: what data is sent and how it is processed. If user registration is enabled in settings, the form can be found at http://joomla.local/index.php/component/users/?view=registration.


A legitimate user registration request looks like the following screenshot.


The com_users component is responsible for working with users. Pay attention to the task parameter in the request. It has the format $controller.$method . Let's look at the file structure.

Names of scripts in the folder controllers correspond to the names of the called controllers. Since our request now contains $controller = "registration" , the file will be called registration.php and its register() method.

Attention, question: how to transfer registration processing to a vulnerable place in the code? You probably already guessed it. The names of the vulnerable and real methods are the same (register), so we just need to change the name of the called controller. Where is our vulnerable controller located? That's right, in the file user.php. It turns out $controller = "user" . Putting everything together we get task = user.register . Now the registration request is processed by the method we need.


The second thing we need to do is send the data in the correct format. Everything is simple here. Legitimate register() expects from us an array called jform , in which we pass registration data - name, login, password, email (see screenshot with the request).

  • /components/com_users/controllers/registration.php: 124: // Get the user data.

125: $requestData = $this->input->post->get("jform", array(), "array");

  • Our client gets this data from an array called user.

/components/com_users/controllers/user.php: 301: // Get the form data.

302: $data = $this->input->post->get("user", array(), "array");

  • Therefore, we change the names of all parameters in the request from jfrom to user .

Our third step is to find a valid CSRF token, since without it there will be no registration.


/components/com_users/controllers/user.php: 296: JSession::checkToken("post") or jexit(JText::_("JINVALID_TOKEN")); CVE-2016-8870 It looks like an MD5 hash, and you can take it, for example, from the authorization form on the site /index.php/component/users/?view=login.

Now you can create users using the desired method. If everything worked out, then congratulations - you just exploited a vulnerability

  • "Missing permission check for registering new users."

This is what it looks like in the “working” register() method from the UsersControllerRegistration controller:

  • /components/com_users/controllers/registration.php: 113: // If registration is disabled - Redirect to login page.

114: if (JComponentHelper::getParams("com_users")->get("allowUserRegistration") == 0) 115: ( 116: $this->setRedirect(JRoute::_("index.php?option=com_users&view= login", false)); 117: 118: return false; 119: )

And so in vulnerable:

/components/com_users/controllers/user.php:

Yeah, no way.

To understand the second, much more serious problem, let's send the request we created and see how it is executed in various parts of the code. Here is the piece that is responsible for validating the user submitted data in the worker method:

Continuation is available only to members Option 1. Join the “site” community to read all materials on the site 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 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. users So, we thought, imagined what fields our form would have and created a table

  • with these fields: id with these fields:- Identifier. Field
  • 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. users That's it, our table

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: DB 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" ; ?> In the folder of our site, create a file with the name This file

will need to be connected to form handlers. Notice the variable, 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 be entered at registration form page(file form_register.php) and the other to the page with 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:


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

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, 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 - To preserve the surname. 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. Name this file handler, 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 In the folder of our site, create a file with the name(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 must check was the form 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 In the folder of our site, create a file with the name.

Error! main page.

"); } ?>

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"]);

Error! 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 = "

You entered the wrong captcha

Error!"; // 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("

"); }

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.

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 - To preserve the surname.. 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."""); 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"] .= "

"; //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. header.php The script for checking the email address format and password length is in the file

, so it will also apply to fields from this form. header.php The session is also started in the file form_auth.php, so in the file


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. 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 After fixing the errors, the button

becomes active, and the user will be able to submit the form to the server, where it will be processed.

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

And so, open the file the authorization handicap has a file specified and write code to process the authorization form. The first thing you need to do is start a session and connect the file In the folder of our site, create a file with the name to connect to the database.

//Declare a cell to add errors that may occur when processing the form.

$_SESSION["error_messages"] = "";

Error!//Declare a cell for adding successful messages $_SESSION["success_messages"] = "";

"); }

/* Check whether the form was submitted, that is, whether the Login button was clicked. If yes, then we move on, if not, then we will display an error message to the user indicating that he accessed this page directly.

Error! 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 = "

*/ if(isset($_POST["btn_submit_auth"]) && !empty($_POST["btn_submit_auth"]))( //(1) Space 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 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 incorrect , then we return the user to the authorization page, and there we will display an error message to him that he entered the wrong captcha $error_message = ".

Error!"; // 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 = "

"); }

The captcha entry 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 email address //(3) Place for processing the password //(4) Place for composing a request to the database )else ( //If the captcha is not passed exit("

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

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

The field for entering a postal address (email) must not be empty.

Email input 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) Password processing area

If the user 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 verification The next field to process is the password field. To the specified place"//(3) Place for password processing

", we write:

Enter your password

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

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

Password field is missing

"; //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 we use the md5() function to encrypt the received password, since our passwords are in encrypted form in the database. An additional secret word in encryption, in our case "" must be the one that was used when registering the user.

Now you need to make a query to the database to select a user whose email address is equal to the received email address and whose password is equal to the received password.

//Query in the database based 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 when selecting a user from the 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 sessions array. $_SESSION["email"] = $email; $_SESSION["password"] = $password; //Return the user to the main page header("HTTP/1.1 301 Moved Permanently"); ."/index.php"); )else( // Save the error message to the session. $_SESSION["error_messages"] .= "

Incorrect login 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(); ) ) Exit from the site And the last thing we implement is

procedure for leaving the site header.php. At the moment, in the header we display links to the authorization page and the registration page. In the site header (file.

), using the session we check whether the user is already authorized. If not, then we display the registration and authorization links, otherwise (if he is authorized), then instead of the registration and authorization links we display the link header.php:

Exit

Modified piece of code from file

Registration Exit 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

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 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):

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

Did you like the article?



New on the site

>

Most popular