the Internet Windows Android

Creating a simple user registration system on PHP and MySQL. Creating a simple user registration system on PHP and MySQL impersonal Index PHP Register

REG.RU: Domains and Hosting

The largest recorder and hosting provider in Russia.

More than 2 million domain names for maintenance.

Promotion, mail for a domain, business solutions.

More than 700 thousand customers worldwide have already made their choice.

* Mouse over to suspend scroll.

Back forward

Creating a simple user registration system for PHP and MySQL

Creating a registration system is a big job. You have to write a code that executes email addresses, sends a message to the mail confirmation, and also performs the validation of the remaining form fields, and much more.

And even after you write all this, users will register reluctantly, because This requires certain efforts on their part.

In this lesson, we will create a very simple registration system that does not require and does not store passwords in general! The result will be easy to change and add to an existing PHP site. Want to figure out how it works? Read below.



Here's how our super simple system will work:

We combine the form of authorization and registration. In this form there will be a field for entering an email address and a registration button;
- When filling out the Email address field, a new user will be created by clicking on the registration button, but only if the email address entered is not found in the database.

After that, a certain random unique set of characters (token) is created, which is sent to the user specified by the user in the form of a reference, which will be relevant within 10 minutes;
- By link, the user goes to our site. The system determines the presence of a token and authorizes the user;

The advantages of this approach:

No need to store passwords and carry out field validation;
- there is no need to restore password, secret questions, etc.;
- from the moment the user has registered / authorized you can always be sure that this user will be in your access area (that the Email address is true);
- incredibly simple registration process;

Disadvantages:

User Account Security. If someone has access to the mail, it can log in.
- Email is not protected and can be intercepted. Keep in mind that this question is relevant and in the case when the password has been forgotten and it must be restored, or in any authorization system that does not use HTTPS for data transfer (login / password);
- While you configure how you need a mail server, there is a chance that messages with links to authorization will be in spam;

Comparing the advantages and disadvantages of our system, it can be said that the system has high yuzability (most convenient for the end user) and, at the same time, has a low security indicator.

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

How to use this system

In the case when you just need to use the system to authorize users on your site, and you do not want to disassemble this lesson on the bones, that's what you need to do:

You need to download sources attached to the lesson
- Find file in the archive tables.sql Import it to 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 communication settings with your database (specify a user and password to communicate with the base as well as the host and name of the base). In the same file, you must also specify email, which will be used as the original address for messages sent by the system. Some hosts block outgoing mails while the form does not specify this email address, which was created from the host control panel, so specify the real address;
- Load all files index.php., protected.php. And the Assets and Includes folders via FTP on your host;
- add the code below to each PHP page, where you need to display the authorization form;

Require_ONCE "includes / main.php"; $ User \u003d NEW User (); if (! $ user- & gtloggedin ()) (redirect ("index.php");)
- Ready!

For those who are interested, how it all works - forward to reading below!

The first step is to write the HTM-code of the authorization form. This code is located in the file. index.php.. This file also contains a PHP code that machines the form data and other useful functions of the authorization system. You can learn more 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 a login link.



In the head section (between tags and) I connected the main styles (in this lesson they do not understand, so you can see them yourself. The ASSETS / CSS / STYLE.CSS folder). To the closing tag

I connected the jQuery library and the script.js file, which we will write and wonder just below.


Javascript.

jQuery tracks the status of the "Register / Authorine" button using the function e.PreventDefault () And sends Ajax requests. Depending on the server response, it displays this or that message and determines further actions /

aSSETS / JS / Script.js

$ (Function () (var form \u003d $ ("# login-register"); form.on ("Submit", Function (E) (if (Form.is (". Loading, .loggedin")) (Return False ;) var email \u003d form.find ("Input"). Val (), MessageHolder \u003d form.find ("Span"); E.PreventDefault (); $ .post (this.action, Email: Email), Function (M) (Form.AddClass ("Error"); MessageHolder.Text (M.Message);) ELSE (Form.RemoveClass ("Error"). AddClass ("Loggedin"); MessageHolder. Text (M.Message);)));)); $ (Document) .Ajaxstart (FUNCTION ();)); $ (Document) .ajaxcomplete (FUNCTION () (Form. Removeclass ("Loading");));));

was added to the form to display the current state of the AJAX request (this became possible due to the methods ajaxstart ()) I. ajaxcomplete ()which you can find closer to the end of the file).

This class shows a spinning animated GIF file (as if hinting that the request is processed), and also acts as a flag that prevents the form of re-sending (when the register button has already been pressed once). Class .loggedin. - This is another flag, is set when email has been sent. This flag instantly blocks any further action with the form.

Database schema

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


User table circuit.

The system does not use passwords, which is visible in the diagram. You can see the column token. with tokens adjacent to column token_validity. The token is installed as soon as the user connects to the system, sets its email to send a message (a little more about this in the next block). Column token_validity Sets the time 10 minutes later, after which the token ceases to be relevant.


Table circuit, which considers the number of authorization attempts.

In both tables, the IP address is stored in the processed form using the IP2Long function in the Integer field.

Now we can write a little PHP code. The main functionality of the system is entrusted to the class User.class.php.which you can see below.

This class actively uses IDORM (DOCS), these libraries are minimally necessary tools to work with databases. It processes access to the database, generation of tokens and their validation. It is a simple interface that allows you to easily connect the registration system to your site if it uses PHP.

User.class.php.

Class User (// Private ORM case Private $ orm; / ** * Find a user on Tocken. Only valid tokens are taken to consideration. Tocken is generated only for 10 minutes from the moment * @param String $ Token. This is the desired Tocken * @return user. Return the value of the function user * / public Static Function Findbytoken ($ token) (// Find a token in the database and make sure that the current time stamp $ result \u003d ORM :: FOR_TABLE ("REG_USERS") -\u003e WHERE ("Token", $ token) -\u003e where_raw ("token_validity\u003e now ()") -\u003e find_one (); if (! $ Result) (Return False;) Return New User ($ Result);) / ** * Authorize or register a user * @param String $ email. Custom email address * @return user * / public address ($ 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 TV in the database and return the value of the function User :: Create 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 \u200b\u200b$ result \u003d orm :: for_table ("reg_users") -\u003e create (); $ result-\u003e email \u003d $ email; $ Result-\u003e Save (); Return New User ($ result);) / ** * Check if such a user exists in the database and return the Variable value of the variable * @param String $ email. Custom Email Address * @return Boolean * / Public Static Function Exists ($ email) (// Is there a user in the database? $ Result \u003d orm :: for_table ("reg_users") -\u003e Where ("Email", $ email) -\u003e count (); return $ result \u003d\u003d 1;) / ** * Create a new user object * @param instance $ param orm, ID, email or 0 * @return user * / public function __construct ($ param \u003d null) (If ($ param instanceof ORM) (// ORM Check is passed $ this-\u003e orm \u003d $ param;) ELSE if (IS_String ($ param)) (// Email checking $ this-\u003e om \u003d om :: for_table ("REG_USERS") -\u003e WHERE ("Email", $ param) -\u003e find_one ();) else ($ id \u003d 0; if (IS_Numeric ($ param)) (// user identifier is transmitted to the value of the $ param $ ID value \u003d $ param;) ELSE if (ISSET ($ _ session ["loginid"])) (// otherwise see the session $ id \u003d $ _session ["Loginid"];) $ this-\u003e orm \u003d orm :: for_table ( "REG_USERS") -\u003e WHERE ("ID", $ ID) -\u003e find_one ();)) / ** * Generate new SHA1 authorization token, writes In the database and returns its value * @return string * / public function generatetoken () (// Generate a token for an authorized user and save it to $ TOKEN \u003d SHA1 ($ this-\u003e email.time (). Rand (0, 1000000 )); // Save tokens in the database // and mark it that it is relevant only within 10 of the following minutes $ this-\u003e orm-\u003e set ("Token", $ token); $ this-\u003e orm-\u003e set_expr ("token_validity", "addtime (now ()," 0:10 ")"); $ this-\u003e om-\u003e save (); Return $ Token; ) / ** * authorize the user * @return void * / public function login () (// Mark a user as authorized $ _session ["loginid"] \u003d $ this-\u003e orm-\u003e ID; // Refresh the value of the Last_Login base field $ this-\u003e om-\u003e set_expr ("last_login", "now ()"); $ this-\u003e orm-\u003e save ();) / ** * destroy the session and divodes the user * @return void * / public function logout () ($ _Session \u003d array (); unset ($ _ session);) / ** * Check, whether the user came * @return boolean * / public function loggedin () (Return Isset ($ this-\u003e orm-\u003e ID) && $ _Session ["LoginID"] \u003d\u003d $ this-\u003e orm-\u003e ID;) / ** * Check is the user administrator * @return boolean * / public function isadmin () (Return $ this-\u003e Rank () \u003d \u003d "Administrator";) / ** * Find a user type, maybe either Administrator or regular * @return string * / public function Rank () (if ($ this-\u003e orm-\u003e Rank \u003d\u003d 1) (Return "Administrator ";) Return" regular ";) / ** * Method allows you to get private infor user account in * quality properties of the user * @Param String $ Key property feature receiving access * @return Mixed * / public function __get ($ Key) (IF (ISSET ($ this-\u003e Ор -\u003e $ Key)) (Return $ this-\u003e orm -\u003e $ Key; ) Return NULL; ))

Tokens are generated using the SHA1 algorithm and are stored in the database. I use MySQL time functions, in order to set a 10-minute restriction of the relevance of the tokeny.

When the token passes the validation procedure, we are directly talking to the handler that we consider only tokens who have no expiration date, stored in the TKEN_VALIDY column.

Note that I use the magic method __get. DOCS libraries at the end of the file to intercept access to the properties of the user object.

Due to this, it becomes possible to access the information stored in the database, thanks to the properties $ User-\u003e Email, $ User-\u003e Token et al. In the following code fragment, consider for an example, how to use these classes.


Protected page

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

functions.php.

Function Send_email ($ from, $ to, $ subject, $ message) (// Helper, sending email $ Headers \u003d "Mime-Version: 1.0". "\\ R \\ n"; $ Headers. \u003d "Content-Type: Text / Plain; Charset \u003d UTF-8 "." \\ R \\ n "; $ Headers. \u003d" From: ". $ from." \\ R \\ n "; Return Mail ($ to, $ Subject, $ Message, $ Headers );) Function Get_Page_URL () (// Determine the US PHP file URL \u003d "HTTP". (Empty ($ _ Server ["https"])? "": "S"). ": //" $ _ Server ["Server_name"]; if (ISSET ($ _ Server ["Request_uri"]) && $ _Server ["Request_uri"]! \u003d "") ($ URL. \u003d $ _Server ["Request_uri"];) ELSE ($ URL. \u003d $ _Server ["path_info"];) Return $ URL;) FUNCTION RATE_LIMIT ($ ip, $ limit_hour \u003d 20, $ limit_10_min \u003d 10) (// The number of input attempts for the last hour on this IP address $ COUNT_HOUR \u003d ORM: : for_table ("reg_login_attempt") -\u003e WHERE ("IP", SPRINTF ("% U", IP2LONG ($ ip))) -\u003e where_raw ("TS\u003e Subtime (now ()," 1:00 ")") -\u003e Count (); // Number of input attempts in the last 10 minutes on this IP address $ Count_10_min \u003d ORM :: FOR_TABLE ("REG_LOGIN_ATTEMPT") -\u003e WHERE ("IP", SPRINT f ("% u", ip2long ($ ip))) -\u003e where_raw ("TS\u003e subtime (now ()," 0:10 ")") -\u003e count (); if ($ count_hour\u003e $ limit_hour || $ count_10_min\u003e $ limit_10_min) (Throw New Exception ("Too Many Login Attempts!");)) Function rate_Limit_Tick ($ ip, $ email) (// Create a new entry in the table that considers Number of input attempts $ login_attempt \u003d ORM :: FOR_TABLE ("REG_LOGIN_ATTEMPT") -\u003e create (); $ login_attempt-\u003e email \u003d $ email; $ login_attempt-\u003e ip \u003d sprintf ("% u", IP2Long ($ ip)); $ login_attempt-\u003e save ();) Function Redirect ($ URL) (Header ("Location: $ URL"); exit;)

Functions rate_limit. and rate_limit_tick. They are followed by the number of authorization attempts for the expired period of time from the moment of the first attempt. The input attempt is recorded in the database in the reg_login_attempt column. These functions are called when processing and sending the form data as you can see from the next code fragment.

The code is taken from the file below. index.php. And it processes the sending of the form. It returns a JSON response, which, in turn, is processed by jQuery in the file aSSETS / JS / Script.jswhich we have already disassembled 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. Whether the user is allowed to log in, does it exceed the number of permissible connections? (Functions.php file for more information) rate_limit ($ _ server ["remote_addr"]); // Record this attempt to authorize Rate_Limit_Tick ($ _ Server ["Remote_ADDR"], $ _Post ["email"]); // Send a letter to the user $ message \u003d ""; $ email \u003d $ _post ["email"]; $ subject \u003d "Your Login Link"; if (! User :: Exists ($ email) ) ($ subject \u003d "thank you for registering!"; $ message \u003d "Thank you for Registering at OUR Site! \\ N \\ n";) // Attempt to authorize or register the user $ User \u003d User :: LoginorRegister ($ _ post [ "Email"]); $ message. \u003d "You can login from this url: \\ n" ; $ message. \u003d get_page_url (). "? TKN \u003d". $ User-\u003e GenerateToken (). "\\ N \\ n"; $ Message. \u003d "The Link Is Going Expire Automatically After 10 Minutes."; $ resulting \u003d send_email ($ Fromemail, $ _post ["email"], $ subject, $ message); If (! $ Result) (Threw New Exception ("There Was An Error Sending Your Email. Please Try Again.");) DIE (JSON_ENCODE (Array ("Message" \u003d\u003e "Thank You! WE \\" Ve Sent A Link To Your Inbox. Check Your Spam Folder AS Well. ")));)) Catch (JSON_ENCODE (Array (Error" \u003d\u003e 1, "Message" \u003d\u003e $ E-\u003e GetMessage () )));)

After successful authorization / registration code, the user will send a link to authorization to the user. Tocken becomes affordable, because It is transmitted as a variable in the generated link method $ _Get. With TKN marker

index.php.

If (ISSET ($ _ get ["TKN"])) (// Is this token valid for authorization? $ User \u003d User :: FindbyToken ($ _ get ["TKN"]); if ($ User) (// Yes is. To make a redirect to the protected page of $ User-\u003e login (); Redirect ("Protected.php");) // No, the token is not valid. Implement a redirect, on the page with the form of authorization / registration of Redirect ("index.php ");)

$ User-\u003e Login ()

create the necessary variables for the session, so that the user, looking through the subsequent site pages, will remain authorized all the time.

Similarly, the processing of the function to exit the system is also arranged.

index.php.

If (ISSET ($ _ get ["logout"])) ($ user \u003d new user (); if ($ user-\u003e loggedin ()) ($ User-\u003e logout ();) redirect ("index.php") ;)

At the end of the code, I again put a redirect on index.php, thus the parameter ? LOGOUT \u003d 1 Not required by the URL is not required.

Our file. index.php. requires add. Protection - We do not want people who ever once logged in the system again saw the registration form. For these purposes, we use the method $ User-\u003e Loggedin ().

index.php.

$ User \u003d NEW User (); if ($ User-\u003e Loggedin ()) (Redirect ("Protected.php");)

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

protected.php.

// To protect each page on your site, connect the file // Main.php to it and create a new User object. That's how easy it is! Require_ONCE "includes / main.php"; $ User \u003d NEW User (); If (! $ User-\u003e Loggedin ()) (Redirect ("index.php");)

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

Echo "Your Email:" $ User-\u003e Email; Echo "Your Rank:" $ User-\u003e Rank ();

Method rank () Used here because the database is usually stored (0 for a regular user, 1 for the administrator) and we need to convert this data to the statuses to which they relate to us and this method helps.

To make an administrator from a regular user, simply edit the user entry via phpMyAdmin (or any other program that allows you to manage databases). Administrator status does not give any privileges, in this example on the page will be displayed that you are an administrator - and that's it.

But what to do with it - it remains at your discretion, you can write and create a code that defines certain privileges and opportunities for administrators.

We finished!

With this incredibly super quasi simple form, we finished! You can use it in your php sites, it's easy enough. You can also modify it under yourself and make it like you want.

Material Prepared Denis Baby specially for site site

P.S. Want to move on in mastering PHP and OOP? Pay attention to premium lessons on various aspects of site buildings, including PHP programming, as well as a free course on creating your CMS system on PHP from zero using OOP:

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


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

1. Let's start with the creation of the networks of Users in the database. It will contain user data (login and password). 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 in another database. Next, set the values \u200b\u200bas in the picture:

2. It is necessary to connect to this table. Let's create a file bd.php.. Its content:

$ db \u003d mysql_connect ("Your MySQL Server", "Login to this Server", "Password to this Server");
mysql_select_db ("name of the base to which you connect", $ db);
?>

In my case it looks like this:

$ db \u003d mysql_connect ("Localhost", "User", "1234");
mysql_select_db ("MySQL", $ db);
?>

Save bd.php..
Excellent! We have a table in the database, the 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):



check in


check in


















4. Create a filewhich will enable data to the database and save the user. save_user.php.(Comments inside):



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


// Remove extra gaps
$ login \u003d trim ($ login);
$ password \u003d trim ($ password);
// Connect to the database
// Check on the existence of a user with the same login
$ result \u003d mysql_query ("Select ID from Users WHERE LOGIN \u003d" $ LOGIN "", $ db);
If (! Empty ($ myrow ["id"])) (
Exit ("Sorry, the login entered already registered. Enter another login.");
}
// If not, we save the data
$ result2 \u003d mysql_query ("Insert Into Users (Login, Password) Values \u200b\u200b(" $ Login "," $ password ")");
// Check if there are errors
if ($ result2 \u003d\u003d "TRUE")
{
Echo "You are successfully registered! Now you can go to the site. Home page";
}
ELSE (
Echo "Error! You are not registered.";
}
?>

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

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


Main page.


Main page.











Register



// Check, whether email variables and user IDs
if (empty ($ _ session ["login"]) or empty ($ _ session ["id"]))
{
// if empty, then we do not display the link
Echo "You entered the site like a guest
This link is available only to registered users. "
}
ELSE.
{

In file index.php. We will withdraw a reference that will be open only for registered users. This is the whole essence of the script - to limit access to any data.

6. There remained a file with checking the entered login and password. TestReg.php (comments inside):

session_start (); // The whole procedure works at sessions. It is in it that the user data is stored while it is on the site. It is very important to launch them at the very beginning of the page !!!
if (isset ($ _ post ["login"])) ($ login \u003d $ _post ["login"]; if ($ login \u003d\u003d "") (Unset ($ Login);)) // We enter the username entered by the user $ login variable if it is empty, then destroy the variable
If (ISSET ($ _ POST ["Password"])) ($ password \u003d $ _ post ["password"]; if ($ password \u003d\u003d "") (Unset ($ password);))
// We enter the password entered by the user in 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 give an error and stop the script
{
EXIT ("You have entered not all the information, go back and fill in all the fields!");
}
// if the login and password are entered, then you process them so that tags and scripts do not work, you never know what people can enter
$ login \u003d stripslashes ($ Login);
$ login \u003d htmlscelchars ($ login);
$ password \u003d stripslashes ($ password);
$ password \u003d HTMLSPECIALCHARS ($ password);
// Remove extra gaps
$ login \u003d trim ($ login);
$ password \u003d trim ($ password);
// Connect to the database
include ("bd.php"); // BD.PHP file must be in the same folder as everyone else, if not, then simply change the way

$ result \u003d mysql_query ("select * from users where login \u003d" $ login "", $ db); // Remove all data about the user from the login from the database.
$ myrow \u003d mysql_fetch_array ($ result);
if (empty ($ myrow ["password"]))
{
// if the user with the login entered does not exist
}
ELSE (
// if there is, then we carry out passwords
if ($ MyRow ["Password"] \u003d\u003d $ password) (
// If passwords match, we start the user's session! You can congratulate it, he entered!
$ _Session ["Login"] \u003d $ myrow ["login"];
$ _Session ["ID"] \u003d $ MyRow ["ID"]; // This data is very often used, here they will "wear with you" included user
Echo "You have successfully entered the site! Main page";
}
ELSE (
// if passwords did not come together

Exit ("Sorry, entered by a Login or password wrong.");
}
}
?>

That's it! Maybe a lesson and boring, but very useful. Only registration idea is shown here, then you can improve it: add protection, design, fields with data, loading avatars, output from the account (for this, just destroy variables from the session with a function unset.) etc. Good luck!

I checked everything, it works fine!

Due to the fact that there are very often questions about global variables and problems associated with the disconnection of the Register_Globals directive, we will try to disclose this topic a bit in this article.

To begin with, we define what external variables are. These are any variables that come to the program from the outside, i.e. Not defined in the program itself. For a script on PHP all variables that are transmitted through a browser string or via form are external.
Consider how they are created.

If the server register_globals \u003d ON (in php.ini) directive is enabled on the server, then when transmitting variables through the form or through the browser string, in the script to which these variables are intended, they will be created automatically. Those. If you have written in the browser row: www.server.ru/index.php?var\u003d1, then the $ var variable will be automatically created in the index.php script with a value of 1.

Comment

The specified directive is one of the most discussion moments in the PHP language. On the one hand, its use can actually generate real problems with the protection of PHP scenarios, in improper accounting of possible erroneous situations and many developers rightly note that writing scripts without the use of global variables by 90% reduces the vulnerability of scripts to various attacks. On the other hand, at the dawn of the appearance of PHP, not one thousand users were entrusted to the developers of the language (to the PHP 4.3 version, this directive was enabled by default), which is currently there are millions of actually functioning scripts written using global variables (worth noting, Which in training purposes is sometimes completely unchecified to write scripts using global variables, since from the replacement for superglobal arrays greatly worsens the readability of the code).

At the moment, most host providers have this directive and, apparently, will remain inclusive for a long time, since otherwise the continuity of the code may be disturbed.

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

  • through associative arrays http _ *** _ VARS (http_post_vars, etc.)
  • through superglobal arrays ($ _env, $ _get, $ _Post, $ _Server, $ _cookie, $ _files, etc.)

Superglobal arrays are available in any area of \u200b\u200bvisibility. PHP developers are recommended to disable register_globals directive on the server and work with variables through superglobal arrays. This recommendation is related to security issues that could occur when the Register_Globals directive is enabled.

Although until recently, on hostings, the register_globals directive remained enabled. The situation began to change with the output of PHP 5, where this default directive is turned off and the hoster is not in a hurry to turn it on (maybe correctly).

So, what exactly do to get variables - you need to take them from superglobal arrays. For example, to obtain variables transmitted through the browser string, use an array of $ _GET. Suppose it is written in the browser string www.server.ru/index.php?var\u003d1, then to obtain a variable var in index.php you need to write:

$ var \u003d $ _ get ["var"];

And, for example, to obtain variables transferred from the form by the POST method in a form-handing script, you need to write:

$ var \u003d $ _ post ["var"];

13.9K.

Hello Dear Web Master, the article tells how dangerous to leave the Register_Globals option turned on. You may have heard that using it can lead to unsafe work of your program (script). But let's figure it out how this option can be used in oppositional purposes and how to protect yourself.

What is REGISTER_GLOBALS?
This option in php.ini, which indicates the need to register the variables received by the POST or GET method into a global $ globals array.

For clarity, I will bring an example when register_globals \u003d ON.
There is a "index.php" file with content:

"; Echo $ Globals [" ASD "]." - Link in the global array $ globals
"; Echo $ _get [" ASD "]." - $ _get ["ASD"] ";?\u003e

In the address bar, write: index.php? ASD \u003d 123

As we can see, 2 variables were created: one local (+ link to $ Globals), the other in the $ _GET array. Many do not use an $ _get array at all, they continue to process the "$ ASD" variable after receiving it from the outside.
But let's think about it, why do we "pollute" the $ globals array? For this, we have special arrays that store the data passed by the GET methods (array $ _GET) and POST (array $ _Post).

The same example, but when register_globals \u003d OFF:

So The local variable was not created and for manipulating with "$ ASD" we must use an $ _get array.

Perhaps now you have changed your opinion about Register_Globals.
You probably have to rewrite something in your programs, but it is worth it.

And now I will tell you how a hacker can take this option for its own purposes, i.e. when register_globals \u003d ON
I will start from simple to complex.

Often we see warnings:

Notice: Undefined Variable: ASD (variable name) in ****

What does it mean? This means that the variable "$ ASD" was not defined explicitly.
For example, some people indulge in similar:

Those. Without determining the variable, immediately begin to use it. The given code in theory is not afraid, but think about it, what if this is the "$ ASD" variable, is the consequence of the file? For example, we will write the following in the address bar: "index.php? ASD \u003d LUXER +" and get: "luser 0123456789". Well, will it be nice to see this? I do not think.

Suppose we write the user authentication system:

I led an obviously holey system, we should only write in the address bar "index.php? Valid_user \u003d 1" and we will get the inscription "Hello, user"

That would not happen if we wrote like this:

Those. They themselves identified the $ Valid_user variable as false in case of failure.

I will give an example with SQL injection:

In the address bar, write: "index.php? Where \u003d id \u003d 0 + Union + All + Select + Login, + password, + null + from + admin + where + login \u003d 'admin'" we get SQL injection:

And the hacker gets your appearance and passwords: (

As you see all the examples, have holes in the protection that can be operated through the register_globals included.

You can cope with this, if you always define a variable regardless of conditions. Or use the encapsulation of variables in functions, i.e. When you define the function, then the variables that inside it will be closed from outside, for example:

Now, if we write in the address bar: "index.php? WHERE \u003d 123"
Give: "$ WHERE does not exist"
But this is provided that you do not install the $ WHERE variable as global, i.e. "Global $ WHERE"

I can come up with a lot of examples, but I think that you will be enough for me to understand.
I want to say that all these problems are round in the summer when you set the Register_Globals \u003d OFF option and try again all the examples above.

It can be done as in php.ini, but most of the hosting providers will not allow you, because you have to use the ".htaccess" file

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

If you have a site on a local computer, then I hope you already have local server is 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 wonderful, otherwise you need to create it. In the article, I explain in detail how to do it.

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

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

So they thought, presented what fields would be our form and create a table users. With such fields:

  • id - Identifier. Field id It must have each table from the database.
  • first_name. - To save the name.
  • last_Name. - To save the last name.
  • email - To save the postal address. E-mail We will use as a login, so this field should be unique, that is, to have an Unique index.
  • email_status. - The field for instructions is confirmed by mail or not. If the mail is confirmed, it will have a value of 1, otherwise the value is 0.
  • password. - To save the password.


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

All, our table users. Ready. Go to the next stage.

Connection to the database

We created a database, now you need to connect to it. Connection will be carried out using PHP expansion MySQLI.

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

Error connecting to database. Error Description: ".mysqli_connect_error ()."

"; EXIT ();) // Set the coding of the $ MYSQLI-\u003e SET_CHARSET connection (" UTF8 "); // For convenience, add a variable here, which will contain the name of our site $ address_site \u003d" http: //testsite.local " ;?\u003e

This file dbconnect.php. It will be necessary to connect to form handlers.

Pay attention to the variable $ Address_Site.Here I indicated the name of my test site, which I will work on. You respectively, specify the name of your site.

Site structure

Now let's figure out with the HTML structure of our site.

The header and the basement of the site will be submitted to individual files, header.php. and footer.php.. We will connect them on all pages. Namely on the main (file index.php.), on the page with the form of registration (file form_register.php.) and on the page with the form of authorization (file form_auth.php.).

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

HEADER.PHP file content:

Name of our website

As a result, the main page, we look like this:


Of course, you can have a completely different structure on the site, but this is not important for us now. The main thing is to have references (buttons) of registration and authorization.

Now let's turn to the form of registration. As you already understood, she is in the file form_register.php..

We go to the database (in phpmyAdmin), open the table structure users. And we look at what fields we need. So we need fields to enter the name and surname, the mail address field (email) and the password input field. And even for security reasons, add a capping field.

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

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

And another moment, if the user is already authorized, and it comes to the registration page directly by writing to the browser in the address bar address_sight / Form_register.php.In this case, in this case, instead of the registration form, we will bring him a headline that it is already registered.

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

You are already registered

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


Via required attribute, we made all the fields mandatory to fill.

Pay attention to the registration code code where the captcha is derived:


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

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

The code is well commented, so I will dwell only at one moment.

Inside the function imagettftext ()indicated path to the font vertana.ttf.. So for the correct work Capcha, we have to create a folder fonts., and put a font file there vertana.ttf.. You can find it and download from the Internet, or take from the archive with the materials of this article.

With HTML structure we finished, it's time to move on.

Verification Email on validity using jQuery

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

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

For this INPUT field, we set the type email (type \u003d "email"), this is a little cautious of incorrect formats. But this is not enough, because through the code inspector, which the browser provides us, you can easily change the attribute value type from email on the tEXT.And all, our check will be invalid.


And in this case, we must make more reliable check. To do this, use Javascript jQuery library.

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

Immediately after this line, add the Email validation check code. Here I will add the code for checking the length of the entered password. Its length should be at least 6 characters.

Using this script, we check the entered postal address on validity. If the user has entered the wrong Email, then we bring it a mistake about this and deactivate the Send shape button. If everything is fine, then we remove the error and activate the send button.

And so, with a shape check on the client part we have finished. Now we can send it to the server where you will also make a couple of checks and add data to the database.

User registration

Form we send to processing the file register.php., through the POST method. The name of this handler file is indicated in the attribute value. action.. And the send method is indicated in the attribute value. method..

Open this file register.php. And the first thing we need to do is write a function of launching the session and connect the previously created file dbconnect.php. (In this file, we have connected to the database). And also, immediately declare cells error_Messages. and success_Messages. In the global array of session. IN error_mesages. We will record all error messages arising during form processing, and in succes_messages.We will write joyful messages.

Before you continue, we must check was there a form at all. The attacker can look at the attribute value action. From the form, and find out which file is engaged in processing this form. And he may come to mind the thought of moving directly to this file, dialing in the address bar of the browser such an address: http: //ares_site/register.php.

Therefore, we need to check the presence of a cell in the POST global array, the name of which corresponds to the name of our "Register" button from the form. So we check whether the "Register" button is pressed or not.

If the attacker tries to go directly to this file, he gets an error message. I remind you that the $ address_site variable contains the name of the site and it was announced in the file dbconnect.php..

Error! Main page.

"); } ?>

The value of captcha in the session was added when generating it, in the file captcha.php.. To remind you show this piece of code from the file captcha.php.where the value of captcha is added to the session:

Now proceed to the check itself. In file register.php., inside the IF block, where you check whether the "Register" button was pressed, or rather where the comment is indicated. " // (1) Place for the next piece of code"We write:

// Check the resulting captcha // Cut the gaps from the beginning and from the end of the $ Captcha \u003d Trim ($ _ post ["CAPTCHA"]); If (ISSET ($ _ POST ["CAPTCHA"]) &&! Empty ($ Captcha)) (// Compare the value with the value from the session. If ((($ _ session ["Rand"]! \u003d $ CAPTCHA) && ($ _session ["RAND"]! \u003d "")) (// If the pin is not correct, then we return the user to the registration page, and there will give him a message about the error that he introduced the wrong capping. $ error_message \u003d "

Error! You entered the wrong capping

"; // We save an error message in the session. $ _Session [" error_messages "] \u003d $ error_message; // Return the user to the Header registration page (" HTTP / 1.1 301 Moved Permanently "); Header (" Location: ". $ Address_Site . "/ Form_register.php"); // Start the Exit script ();) // (2) Place for the next piece of code) ELSE (// If the captcha is not transmitted or it is empty exit ("

Error! There is no check code, that is, Cappitch code. You can go to the main page.

"); }

Next, we need to process the data obtained, from the POST massif. First of all, we need to check the contents of the Global POST massif, that is, whether the cells are there, the names of which correspond to the names of the INPUT fields from our form.

If the cell exists, then cut the spaces from the beginning and from the end of the line from this cell, otherwise, redirecting the user back to the registration form page.

Next, after cutting the spaces, add a string to the variable and check this variable to the void, if it is not empty, then we go further, otherwise you are redirected the user back to the page with the registration form.

This code insert into the specified location " // (2) Place for the next piece of code".

/ * We check if in the global array $ _post exist data sent from the form and conclude the transmitted data to normal variables. * / If (ISSET ($ _ post ["first_name"])) (// Cut the spaces from the beginning and from the end of the $ first_name string \u003d Trim ($ _ post ["first_name"]); // Check the variable to the void if_name (! Empty ($ first_name)) (// For security, we transform special characters in the HTML Entity $ first_name \u003d HTMLSpecialCHARS ($ first_name, ent_quotes) ;) ELSE (// We save an error message in the session. $ _session ["error_messages"]. \u003d "

Specify your name

Missing field named

"; // Return a user to the Registration page Header (" HTTP / 1.1 301 Moved Permanently "); Header (" Location: ". $ Address_Site." / Form_register.php "); // Start the EXIT Script ();) if ( Isset ($ _ POST ["Last_Name"])) (// Cut the spaces from the beginning and from the end of the $ Last_name \u003d Trim ($ _ post ["last_name"]); if (! Empty ($ last_name)) (// for security , We transform special characters in the HTML essence of $ Last_Name \u003d HTMLSPECIALCHARS ($ last_name, ent_quotes);) ELSE (// We save an error message to the session. $ _session ["error_messages"]. \u003d "

Specify your lastname

"; // Return a user to the header registration page (" HTTP / 1.1 301 MOVED PERMANENTLY "); Header (" Location: ". $ Address_site." / Form_register.php "); // Start the Exit script ();)) ELSE (// We save an error message in the session. $ _Session ["error_messages"]. \u003d "

Missing field with last name

"; // Return a user to the Registration page Header (" HTTP / 1.1 301 Moved Permanently "); Header (" Location: ". $ Address_Site." / Form_register.php "); // Start the EXIT Script ();) if ( Isset ($ _ POST ["Email"])) (// Cut the spaces from the beginning and from the end of the $ email \u003d trim ($ _ post ["email"]); if (! empty ($ email)) ($ email \u003d htmlspecialchars ($ email, ent_quotes); // (3) The location of the code to check the format of the postal address and its uniqueness) ELSE (// We save an error message in the session. $ _session ["error_messages"]. \u003d "

Specify your email

"; // Return a user to the header registration page (" HTTP / 1.1 301 MOVED PERMANENTLY "); Header (" Location: ". $ Address_site." / Form_register.php "); // Start the Exit script ();)) ELSE (// We save an error message in the session. $ _Session ["error_messages"]. \u003d "

"; // Return a user to the Registration page Header (" HTTP / 1.1 301 Moved Permanently "); Header (" Location: ". $ Address_Site." / Form_register.php "); // Start the EXIT Script ();) if ( Isset ($ _ POST ["Password"])) (// Cut the spaces from the beginning and from the end of the $ password \u003d trim ($ _ post ["password"]); if (! empty ($ password)) ($ password \u003d htmlscelchars ($ password, ent_quotes); // Enciprate Paparol $ password \u003d MD5 ($ password. "TOP_SECRET");) ELSE (// We save an error message to the session. $ _session ["error_messages"]. \u003d "

Specify your password

"; // Return a user to the header registration page (" HTTP / 1.1 301 MOVED PERMANENTLY "); Header (" Location: ". $ Address_site." / Form_register.php "); // Start the Exit script ();)) ELSE (// We save an error message in the session. $ _Session ["error_messages"]. \u003d "

"; // Return the user to the Header registration page (" HTTP / 1.1 301 Moved Permanently "); Header (" Location: ". $ Address_Site." / Form_register.php "); // Start the Exit script ();) // (4) Place for the code of adding a user in the database

Special importance has a field email. We must check the format of the received postal address and its uniqueness in the database. That is, there is no longer any user with the same email address.

In the specified place " // (3) Code location to verify the format of the postal address and its uniqueness"Add the following code:

// Check the format of the received postal address using a regular expression $ reg_email \u003d "/^**@ (+ (+) )* (.) + +/i"; // If the format of the received postal address does not correspond to a regular expression if (! Preg_match ($ reg_email, $ email)) (// We save an error message in the session. $ _Session ["error_messages"]. \u003d "

You have entered unpaid email

"; // Return the user to the Header registration page (" HTTP / 1.1 301 Moved Permanently "); Header (" Location: ". $ Address_Site." / Form_register.php "); // Start the Exit script ();) // Checking if there is already such an address in the database. $ Result_query \u003d $ Mysqli-\u003e Query ("Select` email` From `users` Where` email` \u003d" ". $ Email." ""); // If the number of received Rows exactly unity, which means the user with such a postal address is already registered if ($ result_query-\u003e num_rows \u003d\u003d 1) (// If the resulting result is not equal to false if (($ ROW \u003d $ result_query-\u003e fetch_assoc ())! \u003d FALSE) (// We save an error message in the session. $ _Session ["error_messages"]. \u003d "

The user with such a post address is already registered

"; // Return the user to the Header registration page (" HTTP / 1.1 301 Moved Permanently "); Header (" Location: ". $ Address_Site." / Form_register.php ");) ELSE (// We save an error message in the session . $ _Session ["Error_Messages"]. \u003d "

Error in the database request

"; // Return the user to the header registration page (" HTTP / 1.1 301 Moved Permanently "); Header (" Location: ". $ Address_site." / Form_register.php ");) / * Clearing sampling * / $ Result_Query-\u003e close (); // stop the Exit script ();) / * closing the sample * / $ result_query-\u003e close ();

And so, we finished with all the checks, it's time to add a user to the database. In the specified place " // (4) Place for the code of adding a user in the database"Add the following code:

// Request for adding a user in the database $ result_query_insert \u003d $ mysqli-\u003e Query ("Insert Into`s" (first_name, last_name, email, password) Values \u200b\u200b(". $ First_name." "," ". $ Last_Name." "," "$ email." "," ". $ password." ")"); If (! $ result_query_insert) (// Save an error message in the session. $ _session ["error_messages"]. \u003d "

Error request for adding user in database

"; // Return a user to the Header registration page (" HTTP / 1.1 301 Moved Permanently "); Header (" Location: ". $ Address_Site." / Form_register.php "); // Start the Exit script ();) ELSE ( $ _Session ["SUCCESS_MESSAGES"] \u003d "

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

"; // send a user to the HEADER authorization page (" HTTP / 1.1 301 Moved Permanently "); header (" Location: ". $ Address_site." / Form_auth.php ");) / * Completion of the request * / $ result_Query_insert-\u003e close (); // Close the connection to the database $ Mysqli-\u003e Close ();

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

Otherwise, if everything went well, in the session we also add a message, but it is already more pleasant, namely we speak the user that registration has passed successfully. And redirect it already to the page with the form of authorization.

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

Launch session also occurs in the file header.php.so in the file form_auth.php. You do not need to run the session, because we get a mistake.


As I said, the script for checking the format of the postal address and the password length here also acts. Therefore, if the user enters the wrong mailing address or a short password, it immediately receive an error message. And button to come in It will not be active.

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

User authorization

In the value of the attribute action. The form of authorization is specified file auth.php.This means that the form will be processed in this file.

And so, open the file auth.php. And write code for processing an authorization form. The first thing you need to do is run the session and connect the file dbconnect.php. To connect to the database.

// declare a cell to add errors that may occur during form processing. $ _Session ["error_messages"] \u003d ""; // declare a cell to add successful messages $ _session ["Success_Messages"] \u003d "";

/ * We check whether the form was sent, that is, a button is pressed to enter. If yes, then we go further if not, then you will withdraw the user a message about the error, that he came to this page directly. * / if (ISSET ($ _ POST ["BTN_SUBMIT_AUTH]) &&! Empty ($ _ post [" btn_submit_auth "])) (// (1) Place for the next piece of code) ELSE (Exit ("

Error! You visited this page directly, therefore there is no data for processing. You can go to the main page.

"); }

// Check the received captcha IF (ISSET ($ _ POST ["CAPTCHA"])) (// Cut the spaces from the beginning and from the end of the $ CAPTCHA \u003d TRIM string ($ _ post ["Captcha"]); if (! Empty ($ CAPTCHA )) (// Compare the value with the value from the session. If (($ _ session ["Rand"]! \u003d $ CAPTCHA) && ($ _session ["RAND"]! \u003d "")) (// If the captcha is not true , We return the user to the authorization page, and there will give him a message about the error that he introduced the wrong capping. $ error_message \u003d "

Error! You entered the wrong capping

"; // We save an error message in the session. $ _Session [" error_messages "] \u003d $ error_message; // Return the user to the HEADER authorization page (" HTTP / 1.1 301 MOVED PERMANENTLY "); Header (" Location: ". $ Address_Site . "/ Form_auth.php"); // Start the Exit script ();)) ELSE ($ error_message \u003d "

Error! The capping field should not be empty.

"; // We save an error message in the session. $ _Session [" error_messages "] \u003d $ error_message; // Return the user to the HEADER authorization page (" HTTP / 1.1 301 MOVED PERMANENTLY "); Header (" Location: ". $ Address_Site . "/ Form_auth.php"); // Start the Exit script ();) // (2) Place for processing postal address // (3) Password processing space // (4) Place to compile a request to the database) ELSE (// If the captcha is not transmitted to Exit ("

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

"); }

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

Checking post address

// Cut the spaces from the beginning and from the end of the $ email \u003d trim ($ _ post ["email"]); if (ISSET ($ _ POST ["Email"])) (if (! Empty ($ email)) ($ email \u003d htmlspecialchars ($ email, ent_quotes); // Check the format of the received postal address using a regular expression $ reg_email \u003d " /^**@ (+ (* +)).) ++/i "; // If the format of the received postal address does not match the IF regular expression (! preg_match ($ reg_email, $ email)) (// We save in the session Error message. $ _session ["error_messages"]. \u003d "

You entered the wrong email

"; // Return a user to the HEADER authorization page (" HTTP / 1.1 301 Moved Permanently "); Header (" Location: ". $ Address_Site." / Form_Auth.php "); // Start the Exit script ();)) ELSE (// We save an error message in the session. $ _Session ["error_messages"]. \u003d "

The mail address field (email) should not be empty.

"; // Return a user to the header registration page (" HTTP / 1.1 301 MOVED PERMANENTLY "); Header (" Location: ". $ Address_site." / Form_register.php "); // Start the Exit script ();)) ELSE (// We save an error message in the session. $ _Session ["error_messages"]. \u003d "

There is no field for entering email

"; // Return a user to the HEADER authorization page (" HTTP / 1.1 301 Moved Permanently "); Header (" Location: ". $ Address_Site." / Form_auth.php "); // Start the Exit script ();) // (3) Password processing space

If the user entered the mailing address in the wrong format or the value of the mail address field is empty, then we return it to the authorization page where we bring it a message about it.

Password check

The next processing field is a password field. In the specified location " // (3) Place for password processing", We write:

If (ISset ($ _ post ["password"])) (// Cut the spaces from the beginning and from the end of the $ password \u003d trim ($ _ post ["password"]); if (! Empty ($ password)) ($ password \u003d HTMLSPECIALCHARS ($ password, ent_quotes); // Enciprate the password $ password \u003d MD5 ($ password. "top_secret");) ELSE (// Save an error message in the session. $ _session ["error_messages"]. \u003d "

Specify your password

"; // Return the user to the header registration page (" HTTP / 1.1 301 MOVED PERMANENTLY "); Header (" Location: ". $ Address_Site." / Form_Auth.php "); // Start the Exit script ();)) ELSE (// We save an error message in the session. $ _Session ["error_messages"]. \u003d "

Missing password entry field

"; // Return a user to the header registration page (" HTTP / 1.1 301 MOVED PERMANENTLY "); Header (" Location: ". $ Address_Site." / Form_Auth.php "); // Start the Exit script ();)

Here we use the MD5 () function to encrypt the received password, since in the database passwords we are in the encrypted form. Additional secret word in encryption, in our case " tOP_SECRET."There must be that that used and when registering the user.

Now it is necessary to make a request to the database at a user sample whose email address is equal to the received postal address and password is equal to the received password.

// Request in database at the user sample. $ result_query_select \u003d $ Mysqli-\u003e Query ("Select * from` Users` Where email \u003d "". $ email. "" And password \u003d "." $ password. "" "); If (! $ Result_Query_Select) (// We save an error message to the session. $ _session ["error_messages"]. \u003d "

Request error at the user sample from the database

"; // Return the user to the Header registration page (" HTTP / 1.1 301 Moved Permanently "); Header (" Location: ". $ Address_Site." / Form_Auth.php "); // Start the Exit script ();) ELSE ( // Check if there is no user with such data in the database, then display an IF error message ($ result_query_select-\u003e num_rows \u003d\u003d 1) (// If the entered data coincides with the data from the database, then we save the login and password to the array of sessions. $ _Session ["email"] \u003d $ email; $ _session ["password"] \u003d $ password; // Return a user to the header home page ("HTTP / 1.1 301 Moved Permanently"); Header ("Location:". $ Address_site . "/ index.php");) ELSE (// Save an error message to the session. $ _session ["error_messages"]. \u003d "

Incorrect username and / or password

"; // Return a user to the HEADER authorization page (" HTTP / 1.1 301 MOVED PERMANENTLY "); header (" Location: ". $ Address_Site." / Form_Auth.php "); // Start the Exit script ();))

Exit from site.

And the last thing we realize is exit procedure from the site. At the moment, in the header we offer links to the authorization page and on the registration page.

In the site cap (file header.php.), Using the session, we check whether the user is already authorized. If not, we display links and authorization links, otherwise (if it is authorized), instead of registration and authorization links, we display a link Output.

Modified piece of code from the file header.php.:

check in

Output

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

File code logout.php:

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

We also learned to check the entered data 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 of exit from the site.

All scripts are checked and workers. You can download the archive with the files of this small site on 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 rebooting the page). So, in order to be aware of the release of new articles, you can subscribe to my site.

If you have questions, please contact, too, if you have noticed some error in the article I ask you, let me know about it.

Lesson Plan (Part 5):

  1. Create an HTML structure for the authorization form
  2. Processing the data obtained
  3. Tell the user's greeting in the header of the site

Did you like the article?