Why is it dangerous to enable the PHP register_globals parameter? Creating a simple user registration system in PHP and MySQL Impersonal index php register

Hello! Now we will try to implement the simplest registration on the site 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 a 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/). We 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 bd.php file. Its content:

In my case it looks like this:

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

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



Registration


Registration


Your login:




Your password:








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

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




Home page


Home page


Your login:


Your password:






Register



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

I checked everything, it works properly!

Reg.ru: domains and hosting

The largest registrar and hosting provider in Russia.

More than 2 million domain names in service.

Promotion, domain mail, business solutions.

More than 700 thousand customers around the world have already made their choice.

*Mouse over to pause scrolling.

Back forward

Creating a simple user registration system in PHP and MySQL

Creating a registration system is a lot of work. You have to write code that validates email addresses, sends an email confirming registration, and also validates other form fields, and much more.

And even after you write all this, users will be reluctant to register, because... this requires some effort on their part.

In this tutorial, we will create a very simple registration system that does not require or store passwords at all! The result will be easy to modify and add to an existing PHP site. Want to find out how it works? Read below.



Here's how our super simple system will work:

We will combine the authorization form and registration. This form will have a field for entering your email address and a registration button;
- When filling out the field with an email address, clicking on the registration button will create a record about a new user, but only if the entered email address was not found in the database.

After this, a random unique set of characters (token) is created, which is sent to the email specified by the user in the form of a link that will be relevant for 10 minutes;
- The link takes the user to our website. The system determines the presence of a token and authorizes the user;

Advantages of this approach:

There is no need to store passwords or validate fields;
- There is no need to recover your password, security questions, etc.;
- From the moment a user registers/logs in, you can always be sure that this user will be in your access zone (that the email address is true);
- Incredibly simple registration process;

Flaws:

User account security. If someone has access to the user's mail, they can log in.
- Email is not secure and can be intercepted. Keep in mind that this question is also relevant in the case where the password has been forgotten and needs to be restored, or in any authorization system that does not use HTTPS for data transfer (login/password);
- While you configure your mail server properly, there is a chance that messages with authorization links will end up in spam;

Comparing the advantages and disadvantages of our system, we can say that the system has high usability (maximum convenience for the end user) and, at the same time, has a low security indicator.

So it is suggested to use it for registrations on forums and services that do not work with important information.

How to use this system

In case you just need to use a system to authorize users on your site, and you don’t want to take this lesson to pieces, here’s what you need to do:

You need to download the sources attached to the lesson
- Find the tables.sql file in the archive. Import it into your database using the import option in phpMyAdmin. Alternative way: open this file through a text editor, copy the SQL query and execute it;
- Open includes/main.php and fill in the settings for connecting with your database (specify the user and password for connecting with the database, as well as the host and name of the database). In the same file, you must also specify the email, which will be used as the original address for messages sent by the system. Some hosts block outgoing emails unless the form contains a real email address, which was created from the host's control panel, so provide a real address;
- Upload all index.php , protected.php files and assets and includes folders via FTP to your host;
- Add the code below to each PHP page where you want to display the login form;

Require_once "includes/main.php"; $user = new User(); if(!$user->loggedIn())( redirect("index.php"); )
- Ready!

For those who are interested in how it all works, read on below!

The first step is to write the HTM code for the authorization form. This code is located in the index.php file. This file also contains PHP code that handles form data and other useful login system functions. You can learn more about this in the section below dedicated to the PHP code review.

index.php

Tutorial: Super Simple Registration System With PHP & MySQL Login or Register

Enter your email address above and we will send
you a login link.

Login/Register

In the head section (between the and tags) I included the main styles (they are not covered in this tutorial, so you can look at them yourself. Folder assets/css/style.css). Before the closing tag, I included the jQuery library and the script.js file, which we will write and analyze below.


JavaScript

jQuery tracks the state of the "Register/Login" button using the function e.preventDefault() and sends AJAX requests. Depending on the server response, it displays one or another message and determines further actions/

assets/js/script.js

$(function())( var form = $("#login-register"); form.on("submit", function(e)( if(form.is(".loading, .loggedIn"))( return false ; ) var email = form.find("input").val(), messageHolder = form.find("span"); e.preventDefault(); $.post(this.action, (email: email), function (m)( if(m.error)( form.addClass("error"); messageHolder.text(m.message); ) else( form.removeClass("error").addClass("loggedIn"); messageHolder. text(m.message); ) )); )); $(document).ajaxStart(function())( form.addClass("loading"); )); $(document).ajaxComplete(function())( form. removeClass("loading"); )); ));

was added to the form to display the current state of the AJAX request (this was made possible thanks to the methods ajaxStart()) And ajaxComplete(), which you can find towards the end of the file).

This class displays a spinning animated GIF file (as if to hint to us that the request is being processed), and also acts as a flag to prevent the form from being submitted again (when the register button has already been clicked once). The .loggedIn class is another flag - it is set when the email was sent. This flag immediately blocks any further actions with the form.

Database schema

Our incredibly simple logging system uses 2 MySQL tables (the SQL code is in the tables.sql file). The first stores data about user accounts. The second stores information about the number of login attempts.


User table schema.

The system does not use passwords, as can be seen in the diagram. On it you can see the token column with tokens adjacent to the token_validity column. The token is installed as soon as the user connects to the system and sets his email to send a message (more on this in the next block). The token_validity column sets the time 10 minutes later, after which the token is no longer valid.


Table schema that counts the number of authorization attempts.

In both tables, the IP address is stored in processed form, using the ip2long function in a field of type integer.

Now we can write some PHP code. The main functionality of the system is assigned to the class User.class.php, which you can see below.

This class actively uses idorm (docs), these libraries are the minimum necessary tools for working with databases. It handles database access, token generation, and token validation. It provides a simple interface that makes it easy to connect a registration system to your site if it uses PHP.

User.class.php

Class User( // Private ORM case private $orm; /** * Find a user by token. Only valid tokens are accepted for consideration. The token is generated only for 10 minutes from the moment it was created * @param string $token. This is the one we are looking for token * @return User Return the value of the User function */ public static function findByToken($token)( // find the token in the database and make sure the correct timestamp is set $result = ORM::for_table("reg_users") ->where ("token", $token) ->where_raw("token_validity > NOW()") ->find_one(); if(!$result)( return false; ) return new User($result); ) /** * Authorize or register a user * @param string $email. User email address * @return User */ public static function loginOrRegister($email)( // If such a user already exists, return the value of the User function from the specified email address stored in the database if(User::exists($email))( return new User($email); ) // Otherwise, create a new user in the database and return the value of the User::create function from the specified email return User::create($email ); ) /** * Create a new user and save to the database * @param string $email. User email address * @return User */ private static function create($email)( // Write a new user and return the result of the User function from these values ​​$result = ORM::for_table("reg_users")->create(); $result->email = $email; $result->save(); return new User($result); ) /** * Check whether such a user exists in the database and return the Boolean value of the variable * @param string $email. User email address * @return boolean */ public static function exists($email)( // Does the user exist in the database? $result = ORM::for_table("reg_users") ->where("email", $email) ->count(); return $result == 1; ) /** * Create a new user object * @param instance $param ORM , id, email or 0 * @return User */ public function __construct($param = null) ( if($param instanceof ORM)( // ORM check passed $this->orm = $param; ) else if(is_string($param))( // Email check passed $this->orm = ORM::for_table ("reg_users") ->where("email", $param) ->find_one(); ) else( $id = 0; if(is_numeric($param))( // the value of the variable $param is passed to the user identifier $id = $param; ) else if(isset($_SESSION["loginid"]))( // Otherwise, see session $id = $_SESSION["loginid"]; ) $this->orm = ORM::for_table( "reg_users") ->where("id", $id) ->find_one(); ) ) /** * Generate a new SHA1 authorization token, writes it to the database and returns its value * @return string */ public function generateToken( )( // Generate a token for an authorized user and save it to the database $token = sha1($this->email.time().rand(0, 1000000)); // Save the token in the database // And mark it as valid only for the next 10 minutes $this->orm->set("token", $token); $this->orm->set_expr("token_validity", "ADDTIME(NOW(),"0:10")"); $this->orm->save(); return $token; ) /** * Authorize the user * @return void */ public function login())( // Mark the user as logged in $_SESSION["loginid"] = $this->orm->id; // Update the value of the last_login database field $this->orm->set_expr("last_login", "NOW()"); $this->orm->save(); ) /** * Destroy the session and log out the user * @return void */ public function logout ()( $_SESSION = array(); unset($_SESSION); ) /** * Check if the user is logged in * @return boolean */ public function loggedIn())( return isset($this->orm->id) && $_SESSION["loginid"] == $this->orm->id; ) /** * Checks whether the user is an administrator * @return boolean */ public function isAdmin())( return $this->rank() = = "administrator"; ) /** * Find the user type, can be either administrator or regular * @return string */ public function rank())( if($this->orm->rank == 1)( return "administrator" "; ) return "regular"; ) /** * Method that allows you to get the user's private information as * properties of the User object * @param string $key The name of the property that gets access * @return mixed */ public function __get($key)( if(isset($this->orm->$key))( return $this->orm->$key; ) return null; ) )

Tokens are generated using the SHA1 algorithm and stored in the database. I'm using MySQL's timing functions to set a 10-minute time limit for a token's validity.

When a token is validated, we directly tell the handler that we are only considering tokens that have not yet expired, stored in the token_validity column.

Please note that I am using the magic method __get docs library at the end of the file to intercept access to the properties of the User object.

Thanks to this, it becomes possible to access information stored in the database thanks to the properties $user->email, $user->token, etc. In the next code fragment, we will look at how to use these classes as an example.


Protected page

Another file that stores useful and necessary functionality is the functions.php file. There are several so-called helpers - assistant functions that allow you to create cleaner and more readable code in other files.

functions.php

Function send_email($from, $to, $subject, $message)( // Helper that sends email $headers = "MIME-Version: 1.0" . "\r\n"; $headers .= "Content-type: text /plain; charset=utf-8" . "\r\n"; $headers .= "From: ".$from . "\r\n"; return mail($to, $subject, $message, $headers ); ) function get_page_url())( // Determine the URL of the PHP file $url = "http".(empty($_SERVER["HTTPS"])?"":"s")."://".$_SERVER ["SERVER_NAME"]; if(isset($_SERVER["REQUEST_URI"]) && $_SERVER["REQUEST_URI"] != "")( $url.= $_SERVER["REQUEST_URI"]; ) else( $url. = $_SERVER["PATH_INFO"]; ) return $url; ) function rate_limit($ip, $limit_hour = 20, $limit_10_min = 10)( // Number of login attempts in the last hour to this IP address $count_hour = ORM: :for_table("reg_login_attempt") ->where("ip", sprintf("%u", ip2long($ip))) ->where_raw("ts > SUBTIME(NOW(),"1:00")") ->count(); // Number of login attempts in the last 10 minutes at this IP address $count_10_min = ORM::for_table("reg_login_attempt") ->where("ip", sprintf("%u", ip2long($ ip))) ->where_raw("ts > SUBTIME(NOW(),"0:10")") ->count(); if($count_hour > $limit_hour || $count_10_min > $limit_10_min)( throw new Exception("Too many login attempts!"); ) ) function rate_limit_tick($ip, $email)( // Create a new record in the table that counts number of login attempts $login_attempt = ORM::for_table("reg_login_attempt")->create(); $login_attempt->email = $email; $login_attempt->ip = sprintf("%u", ip2long($ip)); $login_attempt->save(); ) function redirect($url)( header("Location: $url"); exit; )

Functions rate_limit And rate_limit_tick monitor the number of authorization attempts over the elapsed period of time since the first attempt. The login attempt is recorded in the database in the reg_login_attempt column. These functions are called when the form data is processed and submitted as you can see from the following code snippet.

The code below is taken from the index.php file and it handles the form submission. It returns a JSON response, which in turn is processed by jQuery in the assets/js/script.js file that we looked at earlier.

index.php

Try( if(!empty($_POST) && isset($_SERVER["HTTP_X_REQUESTED_WITH"]))( // Output a JSON header header("Content-type: application/json"); // Is this email address valid if(!isset($_POST["email"]) || !filter_var($_POST["email"], FILTER_VALIDATE_EMAIL))( throw new Exception("Please enter a valid email."); ) // Check. Is the user allowed to log in, has he exceeded the number of allowed connections? (functions.php file for more information) rate_limit($_SERVER["REMOTE_ADDR"]); // Log this login attempt rate_limit_tick($_SERVER["REMOTE_ADDR"], $ _POST["email"]); // Send an email to the user $message = ""; $email = $_POST["email"]; $subject = "Your Login Link"; if(!User::exists($email) )( $subject = "Thank You For Registering!"; $message = "Thank you for registering at our site!\n\n"; ) // Attempt to authorize or register a user $user = User::loginOrRegister($_POST[ "email"]); $message.= "You can login from this URL:\n"; $message.= get_page_url()."?tkn=".$user->generateToken()."\n\n"; $message.= "The link is going to expire automatically after 10 minutes."; $result = send_email($fromEmail, $_POST["email"], $subject, $message); if(!$result)( throw new Exception("There was an error sending your email. Please try again."); ) die(json_encode(array("message" => "Thank you! We\"ve sent a link to your inbox. Check your spam folder as well."))); ) ) catch(Exception $e)( die(json_encode(array("error"=>1, "message" => $e->getMessage() ))); )

After successful login/registration, the code above will send the user a login link. The token becomes available because it is passed as a variable in the generated link by the method $_GET with tkn marker

index.php

If(isset($_GET["tkn"]))( // Is this token valid for authorization? $user = User::findByToken($_GET["tkn"]); if($user)( // Yes , is. Redirect to a protected page $user->login(); redirect("protected.php"); ) // No, the token is not valid. Redirect to a page with an authorization/registration form redirect("index.php "); )

$user->login()

will create the necessary variables for the session, so that the user, viewing subsequent pages of the site, will remain authorized at all times.

The processing of the function to exit the system is arranged in a similar way.

index.php

If(isset($_GET["logout"]))( $user = new User(); if($user->loggedIn())( $user->logout(); ) redirect("index.php") ; )

At the end of the code, I again set a redirect to index.php, so the parameter ?logout=1 transmitted via URL is not required.

Our index.php file requires additional. protection - we don't want people who have logged into the system to see the registration form again. For these purposes, we use the method $user->loggedIn().

index.php

$user = new User(); if($user->loggedIn())( redirect("protected.php"); )

Finally, here is a piece of code that allows you to protect the pages of your site and make it accessible only after authorization.

protected.php

// To protect every page on your site, include a main.php file // and create a new User object. That's how easy it is! require_once "includes/main.php"; $user = new User(); if(!$user->loggedIn())( redirect("index.php"); )

After this check, you can be sure that the user was successfully authorized. You can also access stored information in the database using object properties $user. To display the user's email and status, use this code:

Echo "Your email: ".$user->email; echo "Your rank: ".$user->rank();

Method rank() is used here because the database usually stores numbers (0 for a regular user, 1 for an administrator) and we need to convert this data into the statuses to which they belong, which is what this method helps us with.

To make a regular user an administrator, simply edit the user entry through phpMyAdmin (or any other program that allows you to manage databases). The administrator status does not give any privileges; in this example, the page will display that you are an administrator - and that’s it.

But what to do with this is left to your discretion; you can write and compose code yourself that sets certain privileges and capabilities for administrators.

We're done!

We're done with this incredibly super quasi simple shape! You can use it in your PHP sites, it's quite simple. You can also modify it for yourself and make it the way you want.

The material was prepared by Denis Malyshok specifically for the website

P.S. Do you want to move further in mastering PHP and OOP? Pay attention to premium lessons on various aspects of website building, including programming in PHP, as well as a free course on creating your own CMS system in PHP from scratch using OOP:

Did you like the material and want to thank me?
Just share with your friends and colleagues!


Due to the fact that very often questions arise about global variables and problems associated with disabling the register_globals directive, we will try to cover this topic a little in this article.

First, let's define what external variables are. These are any variables that come into the program from outside, i.e. are not defined in the program itself. For a php script, all variables that are passed through the browser line or through the form are external.
Let's look at how they are created.

If the register_globals = On directive is enabled on the server (in php.ini), then when passing variables through a form or through a browser line, in the script to which these variables are intended, they will be created automatically. Those. if you have the following written in your browser line: www.server.ru/index.php?var=1, then the $var variable with a value equal to 1 will be automatically created in the index.php script.

Comment

This directive is one of the most controversial points in the PHP language. On the one hand, its use can indeed give rise to real problems with the protection of PHP scripts, if possible error situations are not properly taken into account, and many developers rightly note that writing scripts without using global variables reduces the vulnerability of scripts to various types of attacks by 90%. On the other hand, at the dawn of PHP, more than one thousand users trusted the language developers (until PHP 4.3 this directive was enabled by default), due to which there are currently millions of actually functioning scripts written using global variables (It is worth noting that that for educational purposes it is sometimes completely worthwhile to write scripts using global variables, since replacing them with superglobal arrays greatly impairs the readability of the code).

Currently, most host providers have this directive enabled and will likely remain enabled for a long time to come, as otherwise it may break code continuity.

When the register_globals directive is disabled, access to such variables is possible in two ways:

  • via associative arrays HTTP_***_VARS (HTTP_POST_VARS, etc.)
  • through superglobal arrays ($_ENV, $_GET, $_POST, $_SERVER, $_COOKIE, $_FILES, etc.)

Superglobal arrays are available in any scope. PHP developers recommend disabling the register_globals directive on the server and working with variables through superglobal arrays. This recommendation is due to security issues that could arise when the register_globals directive is enabled.

Although until recently, the register_globals directive remained enabled on hosting sites. The situation began to change with the release of PHP 5, where this directive is disabled by default and hosters are in no hurry to enable it (maybe rightly so).

So, what exactly should you do to get variables? You need to take them from superglobal arrays. For example, to get variables passed through the browser line, use the $_GET array. Let's say the browser line says www.server.ru/index.php?var=1. Then to get the var variable in index.php you need to write:

$var=$_GET["var"];

And, for example, to receive variables transferred from a form using the POST method, in the form handler script you need to write:

$var=$_POST["var"];

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

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

Creating a table in the Database

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

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

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

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

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


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

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

Database Connection

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

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

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

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

Site structure

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

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

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

Contents of the header.php file:

Name of our site

As a result, our main page looks like this:


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

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

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

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

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

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

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

You are already registered

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


Using the required attribute, we made all fields mandatory.

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


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

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

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

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

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

Checking email validity using jQuery

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

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

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


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

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

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

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

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

User registration

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

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

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

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

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

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

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

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

Error! You entered the wrong captcha

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

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

"); }

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

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

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

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

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

Enter your name

Name field is missing

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

Please enter your last name

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

Last name field is missing

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

Enter your email

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

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

Enter your password

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

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

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

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

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

You entered an incorrect email

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

A user with this email address is already registered

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

Error in database query

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

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

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

Error in request to add user to database

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

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

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

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

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

The script for checking the email address format and password length is in the file header.php, so it will also apply to fields from this form.

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


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

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

User authorization

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

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

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

File code logout.php:

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

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

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

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

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

Lesson Plan (Part 5):

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

    I don’t know why... no, I know why you can’t enable the register_globals directive, but I don’t know why in the literature, as a rule, nothing is said about this.

    In this article I will try to get all those sitting in it out of the tank and explain what’s what (especially for those on the armored train - editor’s note). It’s not for nothing that some hosters disable this directive. So…

    How it works

    In the PHP settings (php.ini file) there is such a register_globals directive. Its meaning is that if it is enabled (register_globals = on), then all variables passed via GET and POST will be automatically registered as global. What does it mean?

    For example, we pass the GET method to the index.php script some page value: index.php?page=2. The passed value is stored in a GET array and can be used in a script as $_GET["page"]. However, if we have register_globals enabled, then a $page variable will be created for the passed value, which is available in any part of the index.php script.

    A small summary and addition. When register_globals is enabled, three copies of the variable are created: in the GET array, in the GLOBALS array, and simply the variable itself ($_GET["page"], $GLOBALS["page"], $page), while when register_globals is disabled, the passed value can be accessible only through the GET array ($_GET["page"]). Remember.

    Danger of use

    Let's look at a simple example to understand what's in store for us (from 3 to 5 years - editor's note). To make it easier, I’ll say right away that $login and $password are variables passed by the GET/POST method.

    Briefly about what the script does:

      Line 2. We make a request to the database in order to pull out the real password for the login entered by the user.

      Line 3. We get this password and assign it to the $real_pass variable.

      Line 4. We compare the real and entered password and if they match, then the $check variable will be assigned true.

      Lines 5-8. If $check is true, then we write that authorization was successful, etc.

    The proposed scenario, by definition, is the most leaky in the world, and now I will show you these holes. Condition: register_globals is enabled.

    Let's say the transfer is carried out using the GET method. Then the url will look something like this:
    www.site.com/index.php?login =admin&password =qwerty
    It is clear that the global variables $login and $password are immediately created. Now look at the script. It contains the $check variable. What if you pass it via URL?

    www.site.com/index.php?login =admin&password =qwerty&check =1
    Then the password matching check is bypassed and the user is immediately authorized (after all, do you remember that 1 is true, and 0 is false?). The same result will occur if we write www.site.com/index.php?check =1 . And even if you use the POST method, all such frauds will still work, since when register_globals is enabled, it does not matter what method you use - GET or POST.

    I think someone has a question, how does a cracker know about the check variable, that it is responsible for everything? If you haven't shown the script to anyone, they are unlikely to know it. However, not everyone uses their own scripts, CMS, etc., but uses what is available on the network. In such cases, a cracker, for example, can study the CMS code and attack sites created with its help.

    However, not all hosters disable register_globals, and even if your scripts are designed to not have register_globals enabled, a cracker can still hack your script using the vulnerability of this directive.

    Let's take our example. To protect it in case register_globals is enabled, after the line if ($password==$real_pass)$check =true; add the following: else$check =false;. In this case, even if the check variable equal to one is passed by the GET method, the script will still set $check=false if the password is incorrect.

    Yes, I would also like to draw your attention to the fact that if you turn off register_globals, then our example will not work. And for it to work, you need to write $login = $_POST["login"]; $password = $_POST["password"];

    Let's sum it up...

    and draw two main conclusions:

    1) When register_globals is enabled, you can pass various variables, the values ​​for which were not calculated to be received via GET or POST.

    2) Register_globals itself is not so much dangerous as a crookedly written script.

    That's all for today! I will be very glad to see your comments, remarks, suggestions and just feedback. Therefore, write, don’t be shy!

    With wishes for a successful week,
    Alexander SHUYSKY