Why is it dangerous to enable PHP register_globals option? Creating a simple PHP and MySQL user registration system You are already registered.


I don’t know why ... no, why it’s impossible to include the register_globals directive I know, but I don’t know why in the literature, as a rule, nothing is said about it.

In this article I will try to get all those who sit in it out of the tank and explain what's what (especially for those on the armored train - ed.). All the same, it is not in vain that some hosters disable this directive. So…

How it works

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

For example, we pass the index.php script with the GET method some value page: index.php? Page = 2. The passed value is stored in the GET array and can be used in a script as $ _GET ["page"]. However, if we have register_globals enabled, then the $ 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 just the variable itself ($ _GET ["page"], $ GLOBALS ["page"], $ page), while when register_globals is disabled, the passed value can only accessible through the GET array ($ _GET ["page"]). Remember.

Danger of use

Let's consider a simple example to understand what shines for us (from 3 to 5 years - editor's note). To make it easier, I will 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 extract the real password for the login entered by the user.

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

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

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

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

Let's say the transfer is by 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 watch the script. It contains the $ check variable. But what if you pass it through 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 (do you remember that 1 is true and 0 is false?). The same result will be obtained 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 doesn't matter which method you use - GET or POST.

I think someone had a question, how does the cracker know about the check variable, that it is responsible for everything? If you have not shown the script to anyone, then he is unlikely to know. However, not everyone uses their scripts, CMS and so on, but uses what is on the network. In such cases, a cracker, for example, can study the CMS code and make attacks on sites created with it.

However, not all hosters disable register_globals, and even if your scripts are geared towards the absence of 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, you need 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'll also draw your attention to the fact that if you turn off register_globals, then our example will not work. To make it work, you need to write $ login = $ _POST ["login"] before the script; $ password = $ _POST ["password"];

Let's sum up ...

and draw two main conclusions:

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

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

That's it for today! I would be very glad to receive your comments, remarks, suggestions and just feedback. Therefore, write, do not hesitate!

Wish you a good week,
Alexander Shuisky

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

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

Creating a table in the Database

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

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

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

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

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


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

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

Database Connection

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

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

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

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

This file dbconnect.php will need to be hooked up to form handlers.

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

Site structure

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

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

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

Content of header.php file:

Name of our site

As a result, the main page looks like this:


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

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

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

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

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

And one more thing, if the user is already authorized, and for the sake of interest he enters the registration page directly by writing to the address bar of the browser site_address / form_register.php, then in this case, instead of the registration form, we will display a title to him stating that he has already been registered.

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

You are already registered

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


Via required attribute, we have made all fields required.

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


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

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

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

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

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

Checking email validity with jQuery

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

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

For this input field, we 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 with, you can easily change the value of the attribute type With email on the text and that's it, our check will no longer be valid.


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

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

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

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

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

User registration

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

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

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

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

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

Error! home page.

"); } ?>

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

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

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

Error! You entered the wrong captcha

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

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

"); }

Next, we need to process the received data from the POST array. First of all, we need to check the contents of the global POST array, that is, are there cells 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 from the end of the line from this cell, otherwise, we redirect the user back to the page with the registration form.

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

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

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

Enter your name

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 string $ last_name = trim ($ _ POST ["last_name"]); if (! empty ($ last_name)) (// For security , convert special characters to HTML entities $ last_name = htmlspecialchars ($ last_name, ENT_QUOTES);) else (// Save the error message to the session. $ _SESSION ["error_messages"]. = "

Enter your last name

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

Last name field is missing

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

Enter your email

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

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

Enter your password

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

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

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

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

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

You entered an invalid email

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

A user with this 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 the database query

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

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

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

Failed to add a user to the database request

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

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

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

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

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

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

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


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

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

User authorization

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

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

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

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

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

"); }

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

Error! You entered the wrong captcha

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

Error! The field for entering captcha must not be empty.

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

Error! The verification code is missing, that is, the captcha code. You can go to the home page.

"); }

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

Checking the postal address

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

You entered an incorrect email

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

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

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

Email field is missing

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

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

Password check

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

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

Enter your password

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

There is no field for entering a password

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

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

Now you need to make a query to the database on a sample of a user whose mailing address is equal to the received mailing address and the password is equal to the received password.

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

Request error on user fetch from database

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

Incorrect username and / or password

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

Log out from the site

And the last thing we do is procedure for leaving the site... At the moment, the header displays links to the authorization page and to the registration page.

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

Modified piece of code from file header.php:

registration

Exit

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

File code logout.php:

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

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

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

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

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

Lesson plan (Part 5):

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

Did you like the article?

It is likely that you have already heard about register_globals directive and you know what she does. If someone does not know this, then you will learn about it from this article, however, the main task of this article is to prove that register_globals directive it is best to always keep it disabled for security reasons.

Allows you to register variables obtained from GET request... Let's say there was a request like this: index.php? a = 15... This will certainly create a variable $ _GET ["a"] and variable a... Here is the creation of a variable a and it happened as a result enabled directive register_globals.

Now about why this directive should always be kept disabled. Suppose you are authorizing a user and you have written the following code:

if (($ _POST ["login"] == "Admin") && ($ _POST ["password"] == "123456")) $ check_user = true;
if ($ check_user) echo "Authorization was successful";
else echo "Authorization failed";
?>

Now if the file is called, for example, auth.php, then referring to it as follows: auth.php? check_user = 1, then you get a successful authorization, regardless of what login and password were sent and whether they were sent at all.

Of course, this example is slightly mystical, since no one writes like this (at least due to the lack of else $ check_user = false;), however, this example clearly shows what register_globals directive enabled.

Now about how disable the register_globals directive... To do this, add to the file .htaccess just one line:

Php_value register_globals 0

There is a small chance that if the directive was previously enabled, then something may break for you, so check everything carefully and fix any errors that have occurred, since the security is really worth it.

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 principle of our script is shown below.

1. Let's start by creating the users plate in the database... It will contain user data (login and password). Let's go to phpmyadmin (if you create a base 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 picture:

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

$ db = mysql_connect ("your MySQL server", "login to this server", "password to 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);
?>

We save bd.php.
Fine! We have a table in the database, a connection to it. Now you can start creating a page where 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 can 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 username you entered is already registered. Please enter another username.");
}
// if not, then save the data
$ result2 = mysql_query ("INSERT INTO users (login, password) VALUES (" $ login "," $ password ")");
// Check if there are any errors
if ($ result2 == "TRUE")
{
echo "You have successfully registered! You can now enter the site. Home page";
}
else (
echo "Error! You are not registered.";
}
?>

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

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


Home page


Home page











Register now



// 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 restrict access to any data.

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

session_start (); // the whole procedure works on sessions. It is in it that the user's data is stored while he is on the site. It is very important to run 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 variable $ login, if it is empty, then we destroy the variable
if (isset ($ _ POST ["password"])) ($ password = $ _ POST ["password"]; if ($ password == "") (unset ($ password);))
// put the password entered by the user into the variable $ password, if it is empty, then destroy the variable
if (empty ($ login) or empty ($ password)) // if the user did not enter the login or password, then we issue an error and stop the script
{
exit ("You did not enter all the information, go back and fill in 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 can 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"); // bd.php file must be in the same folder as everyone else, 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 passwords
if ($ myrow ["password"] == $ password) (
// if the passwords match, then we start the session for the user! You can congratulate him, he entered!
$ _SESSION ["login"] = $ myrow ["login"];
$ _SESSION ["id"] = $ myrow ["id"]; // this data is very often used, so the logged in user will "carry with him"
echo "You have successfully entered the site! Home page";
}
else (
// if passwords don't match

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

OK it's all over Now! The lesson may be boring, but very useful. Here, only the idea of ​​registration is shown, then you can improve it: add protection, design, data fields, upload avatars, log out of the account (for this, simply destroy the variables from the session with the function unset) etc. Good luck!

I checked everything, it works properly!

In order to divide site visitors into certain groups, a small system must be installed on the site php registration... Thus, you conditionally divide visitors into two groups of just 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 digress a little, and now we will take a closer look at the registration file.

Register.php file

So that it does not take a lot of your time, we will create a system that will collect users, taking minimal contact information from them. 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 the 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 do you need to write everything in one encoding, we'll talk sometime later. Until then, take this information as the strictest rule of thumb for scripting otherwise there will be problems with scripting in the future. It's okay, of course, but you just waste a lot of time looking for errors in the script.

How will the script itself work?

We want to simplify everything and get fast results. Therefore, we will receive from users only login, email and password. 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 written in one file register.php:

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

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







2021 gtavrl.ru.