Inurl php home type id personal account. Creating a simple user registration system in PHP and MySQL


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

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

So, we need the following files:

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

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

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

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

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

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

User authorization

register.

Now our form needs to be given some form. At the same time, we will define rules for other elements. Looking ahead, I will present the contents of the style sheet in full.

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

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

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

User registration

" />

You probably noticed that there are PHP variables in the HTML code. They are the contents of attributes of text fields of forms, the contents of containers designed to display errors. But we haven't initialized these variables. Let's do that.

User registration

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

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

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

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

Now, let's say the user clicked on the registration button and did not fill out the form fields. According to our algorithm, the login and password cannot be empty. If this condition is not met, registration is not possible. We keep in mind that the processing of the form data occurs in the current scenario. This means we need to change its code by adding appropriate checks. Let's immediately discuss the following checks. If you have entered both a login and a password, you need to check their compliance with the specified requirements. To verify the login and password, we will create custom functions in the functions.php file.

/** * functions.php * File with custom functions */ // Connect the file with connection parameters to the DBMS require_once("database.php"); // Checking the username function checkLogin($str) ( // Initialize a variable with a possible error message $error = ""; // If the login line is missing, return an error message if(!$str) ( $error = " You have not entered a username"; return $error; ) /** * Check the username using regular expressions * The login must be no shorter than 4, no longer than 16 characters * It must contain characters of the Latin alphabet, numbers, * it may contain be the characters "_", "-", "." */ $pattern = "/^[-_.a-z\d](4,16)$/i"; $result = preg_match($pattern, $str) ; // If the check fails, return an error message if(!$result) ( $error = "Invalid characters in the username or the username is too short (long)"; return $error; ) // If everything is fine, return the value true return true; ) // Checking the user's password function checkPassword($str) ( // Initialize a variable with a possible error message $error = ""; // If there is no login line, return an error message if(!$ str) ( $error = "You did not enter a password"; return $error; ) /** * Check the user's password using regular expressions * The password must be no shorter than 6, no longer than 16 characters * It must contain Latin characters, numbers, * it may contain the characters "_", "!", " (", ")" */ $pattern = "/^[_!)(.a-z\d](6,16)$/i"; $result = preg_match($pattern, $str); // If check did not pass, return an error message if(!$result) ( $error = "Invalid characters in the user's password or the password is too short (long)"; return $error; ) // If everything is fine, return the value true return true; )

Now we need to modify the registration.php file to enable the functions we declared. We will add a condition to the script that checks whether the register button is clicked. Within this condition, a check of login and passwords is launched. If any of the checks fail, we display the form again and display an error message. If there are no errors, we register the user, we no longer display the registration form, we inform the user about successful registration, and using the header() function we redirect him to the authorization form.

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

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

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

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

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

"); // Don't forget to disconnect from the DBMS mysql_close(); // Return the value true, indicating successful user registration return true; )

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

User authorization

;">

If you are not registered in the system, register.

You probably noticed that in the authorization script we now have another unfamiliar function - authorization() . This function must authorize the user by first checking whether a registered user with the same login and password exists in the database. If such a user is not found, authorization will be aborted and a failure message will be displayed. If the check is successful, the authorization() function will launch a session and write the user's login and password values ​​into it, inform the script that authorization was successful, and the script will redirect the user to a protected resource page.

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

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

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

When a user lands on a protected page, you should check the correctness of his authorization data. To do this we need another custom function. Let's call it checkAuth() . Its task will be to verify the user’s authorization data with those stored in our database. If the data does not match, the user will be redirected to the login page.

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

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

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

Now that the user has arrived at the protected page, we must call the function to check the authorization data. We will place the call and verification script in a separate checkAuth.php file and connect it to those pages that will be closed to public access.

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

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

User authorization and registration

Successful authorization.

You have accessed a secure page. You can log out.

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

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

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

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

From the author: Sooner or later, every web developer is faced with the task of restricting access to a certain page/pages or directory. This could simply be a secret page on the site, the administrative part of the site, or any other section to which we want to restrict access and provide only with a password. To do this, you can, of course, use server tools. I think that any modern hosting has a function for password-protecting a directory, where you can create a user, assign a password to him and, after password-protecting the directory, access to the closed directory will be provided only after entering the correct login and password. But sometimes you want to write something yourself, something quick, simple, but at the same time reliable...

In this lesson we will try to write our own simple authorization system. We will have a secret page - let's say it will be an administrator page, to which we will provide access only to an authorized user. Our authorization system will be based on the session mechanism. Before continuing this lesson, I recommend that you familiarize yourself with one of my previous lessons, in which we, in particular, consider the work of sessions -.

Briefly, all work with sessions can be divided into 3 stages:

Opening of the session. On all pages where work with sessions is implied, the session must be started using the session_start() function.

Registering session variables.

Unregistering session variables using the unset() function and closing the session using the session_destroy() function.

Step 1

So, for our work, we will create 3 files - Home page (index.php), Contacts (contact.php) and Admin panel (admin.php). Please note that the file extension to which we will restrict access should be .php. As you guessed, we will restrict access to the admin.php file. The code for all files is the simplest - it is a kind of menu in a line with links to other pages, and under it the individual text of each page so that we can distinguish them from each other. Here, for example, is the code for the index page:

Home | Contacts | Admin


This is the main page

The remaining pages, as I said, differ from it only in the text after the line tag. I did not create full-fledged pages with meta tags, since our task is only to restrict access to a certain page.

Step 2

For now, we can freely navigate all pages, including the admin page. How can we limit access to it? What will the algorithm be like? We will do the following: at the very beginning of the page we will check whether the label we need is in the session or, more simply put, whether a certain session variable exists (we can also check whether the value of a session variable is equal to a certain value). If there is no such variable, then the user requesting this page is not authorized, which means we will redirect him to the authorization page, where he will be asked to fill out a form with a name and password. The algorithm is extremely simple - let’s implement it. Go to the admin.php file, open the PHP construct at the very top and write the following code:

session_start();

if (! $_SESSION [ "admin" ] ) (

header("Location: enter.php");

exit ;

Let's now read this code. Firstly, we opened a session, as you remember - this is a prerequisite when working with sessions. Next, we created a simple condition that can be read like this: “if the admin element does not exist in the $_SESSION array, we will execute the block of actions enclosed in operator brackets.” And in the code block, using the header() function, we redirect the user to the enter.php page (this is the authorization page). After the header() function, we must complete the execution of the script using the exit() function. If the condition is not met, i.e., there will be an admin element in the $_SESSION array, this means that the user has already been successfully authorized, and we will skip the action block in operator brackets, i.e., no redirect will occur, and we show the requested page.

Step 3

Now we need to create a login page - enter.php. To do this, copy the code, for example, of the contact.php page, create a new file and paste the copied code into it. Save the file under the name enter.php. Now on this page we will write a simple form for entering your login and password:

Home | Contacts | Admin


This is the login page.
Username:
Password:

< p > < a href = "index.php" >home< / a > | < a href = "contact.php" >Contacts< / a > | < a href = "admin.php" >Admin< / a > < / p >

< hr / >

< br / >

< form method = "post" >

Username:< input type = "text" name = "user" / > < br / >

Password:< input type = "password" name = "pass" / > < br / >

< input type = "submit" name = "submit" value = "To come in" / >

< / form >

Everything is simple here. The form has 2 fields: a login field (we gave it the name “user”) and a password field (named “pass”). We also created a button (name “submit”), when clicked, data from the form will be sent. The data is sent using the post method - we specified this in the method attribute of the form tag - and will be processed on the same page. Now we can try to go to the admin page. If everything is done without errors, we will not be able to get there, but will invariably end up on the authorization page.

Amazing!

Step 4

Next, we need to write a handler on the page with the form that will receive data from the form and compare whether the login and password from the form match those that we have. To do this, open the PHP construct at the top of the login page and start writing code. First, we must open a session - after all, this is where we will create a label in the session if we have received the correct login and password. On this same page we will store the administrator's login and password. Usually this data is stored in a database (DB), but we will only have 1 user (administrator), and therefore storing his data to log into the DB is not entirely rational. If there is more than one user, i.e., for example, we are writing a project in which there is registration, then, of course, in this case it will be difficult to do without a database.

So, our login will be “admin” and we will store it in the $admin variable. The password will be “mypass” and it will be stored in the $pass variable. But storing passwords in clear text is not accepted - this is contrary to security principles. We will store the password in encrypted form, and the md5() function will help us encrypt it. This function encrypts a string using a special algorithm, and the output is a string of 32 characters (called a hash). If we encrypt the string “mypass” (this can be done, for example, in the contact.php file):

echo md5 ("mypass" ) ;

then the output will be the line “a029d0df84eb5549c641e04a9ef389e5″ - this will be our encrypted password. For now, the login page code will be like this:

Home | Contacts | Admin


This is the login page.
Username:
Password:

session_start();

$admin = "admin" ;

$pass = "a029d0df84eb5549c641e04a9ef389e5";

< p > < a href = "index.php" >home< / a > | < a href = "contact.php" >Contacts< / a > | < a href = "admin.php" >Admin< / a > < / p >

< hr / >

< br / >

< form method = "post" >

Username:< input type = "text" name = "user" / > < br / >

Password:< input type = "password" name = "pass" / > < br / >

< input type = "submit" name = "submit" value = "To come in" / >

< / form >

Step 5

Now let’s check what we received from the form with what we have in the login and password variables. We will do this conditionally - only if the form button is pressed. How can we check this? The button has a name (“submit”), and we transmit data using the post method. Accordingly, we can simply check if the submit element exists in the $_POST array. If there is, the button was pressed, and we will perform actions to verify the sent data, otherwise we will not do anything. After declaring the login and password, we write the condition:

if($_POST["submit"])( if($admin == $_POST["user"] AND $pass == md5($_POST["pass"]))( $_SESSION["admin"] = $ admin; header("Location: admin.php"); exit; )else echo "

Login or password is incorrect!

"; }

if ($_POST["submit"]) (

if ($ admin == $_POST [ "user" ] AND $ pass == md5 ( $ _POST [ "pass" ] ) ) (

$_SESSION["admin"] = $admin;

exit ;

) else echo "

Login or password is incorrect!

" ;

We made the condition for checking the login and password double. This is done using the logical operator AND (it can also be written this way - “&&”). The condition can be read as follows: “if (the $admin variable is equal to the user element in the $_POST array AND the $pass variable is equal to the hash of the pass element in the $_POST array) then (we perform the block of actions)else we display the text ‘Login or password is incorrect!’

If the login-password pair matches, then we register the session variable $_SESSION["admin"] and redirect the user to the admin page - admin.php.
Let's now try to test what we have already created. If we enter a deliberately false login and password, we will receive a warning message that “Login or password is incorrect!” Let's now try to enter the correct login information. If we haven’t made a mistake anywhere, then after clicking on the “Login” button we will find ourselves on the admin page.

Step 6

Now all that's left to do is add some minor details. For example, we are now authorized in the system, but if we enter the address of the authorization page in the address bar, we will easily get to it and see the authorization form. This should not happen - only an unauthorized user should see the form. How can we fix this? Remember that on the admin.php page we checked whether the label was in the session. If it is not there, we redirected the user to the authorization page. Here we can do the same thing, only in reverse. That is, we also check if the label is in the session. Only now we will transfer the user to the admin page if there is such a label. This is, in principle, logical. If there is a label, then the user is already authorized, and we can transfer him to the admin page. On the enter.php page after the session starts, add the following code:

if($_SESSION["admin"])( header("Location: admin.php"); exit; )

if ($_SESSION["admin"]) (

header ("Location: admin.php" ) ;

exit ;

Now, if an authorized user tries to enter the name of the authorization page in the address bar, he will be redirected to the admin page. An unauthorized user will be able to freely access the authorization page.

Step 7

The next point that we need to provide is the implementation of the logout of an authorized user, i.e., let’s say the administrator has finished his work and needs to log out so that no one else can work under his account. To do this, add an “Exit” link to the admin.php page. The link will lead to the same page, only the parameter we need will be added to it. The parameter is added using a question mark:

Exit

< a href = "admin.php?do=logout" >Exit< / a >

This link can be placed in the place where we need it - I will put it after the page text. Regarding the parameter, it will be transmitted using the GET method (remember that we transmitted data from the form using the second parameter - POST). When using this method, the data is appended to the address in the address bar and is separated from the address by just a question mark. We pass one parameter - do - and at the same time assign it the value "logout". How can we authorize the user now? It’s very simple - the second and third stages will help us here when working with sessions. When the page loads, we can check the value of the do element from the $_GET array. If it is equal to the string “logout”, we will simply unregister the session variable $_SESSION["admin"] and destroy the session. Accordingly, there will be no label in the session after this, and in the next block, where we check for the presence of the label, the user will be redirected to the authorization page. It's simple.

Hi all. So we've learned a few elements to create shapes. It's time to combine our knowledge to solve a bigger problem. Let's create the simplest form for authorization on the site. To do this, we need two fields, we create and attach signatures to them.

The first field is for the login, the second is for the password. And with the second one it’s not so simple. Because at the moment it is just a text input field.

Result in browser:

In order for the text entered in it to be replaced with asterisks, as is customary for a field of this type, you need to do one simple action. Namely, to replace the attribute value type on password:

Result:

Form submit button

Here you go. Our form is almost ready. Now, to complete its creation, you need to create a button that will be used to submit the form. The problem is solved using a tag with type submit.

If the button should have some kind of inscription, then it can be done using the attribute value. It is up to you to assign a name to the button or not; if you do this, the server will receive this name, as well as the value of the button.

As a rule, the name of a form submit button is needed when the form has several buttons, each of which performs a specific action. Thanks to this, the server, receiving the name and value of the button from the browser, understands which button the user clicked and what, accordingly, needs to be done.

As a result, the code for our form will be as follows:

Result in browser:

I bring to your attention a very simple and functional registration and authorization script on the site, which consists of 3 PHP files with the connection of 2 java scripts, with the help of which errors are displayed in the form itself without reloading the page.

The script has been successfully tested on PHP 5.3.3 and PHP 5.6.3

What the script can do and has

  • Register new users;
  • Authorize users and record cookies for a certain period (no need to log in each time);
  • Show and hide certain information for authorized and unauthorized users, respectively;
  • Has an ADMIN PANEL where you can edit all data and delete users.

DEMO and Admin Panels are also there

STEP 1.
If you use the local registration and authorization script using DENWER, then you do not need to make changes to the files to connect to the database.
Otherwise, open the files: stayt.php, classes/Auth.class.php and adminka/connect.php, and at the very top replace the data for connecting to the database with yours.

STEP 2.
Go (if you use DENWER) to the address: http://localhost/Tools/phpmyadmin/, if on hosting, then click Databases and create a new database with the name: registr and comparison: utf8_general_ci.
You can, of course, set your own name, but then be sure to replace it in the files to connect to the database (see step 1).

STEP 3.
Click on the created registr database and then on the top SQL tab and in the input window that appears, paste this code and click OK.

CREATE TABLE IF NOT EXISTS `my_users` (`id` int(11) NOT NULL AUTO_INCREMENT, `username` varchar(255) NOT NULL, `names` varchar(15) NOT NULL, `password` varchar(255) NOT NULL, `salt` varchar(100) NOT NULL, PRIMARY KEY (`id`)) ENGINE=MyISAM DEFAULT CHARSET=utf8;

All! Go to your address in the browser, try and experiment.

Admin panel

After you have completed at least one registration, you can go to the ADMIN section.
Login to the ADMIN PANEL:

Http://your_site.ru/adminka/

Don't forget to secure this folder and you can also rename it.
When you open the Admin Panel, click the SEARCH button and all registered users will be displayed to you, where when you click on a specific ID number, you will see the user data for editing.

You can also quickly find a user by his E-mail; to do this, just enter a known e-mail in the SEARCH field and click on the button.
I do not recommend using the ADD button, since the user is added to the system without a password. And I have no idea why they even made it.

That's all, if it doesn't work out or isn't clear, ask questions.


At the same time, you can try to sell information (products).

The function of registering and authorizing users on the site is implemented as follows: when a user registers on the site, he fills out a registration form in which he indicates various data, including login and password. The form sends this data to the server and it is written to the database.

  1. The user enters the login and password into the authorization form and sends it to the server.
  2. The server checks whether there is a user in the database with the same login and password.
  3. If the user is found, information about this is recorded in a session or cookie.
  4. On the site pages, a check is made to see if the session contains data that the user is authorized and, depending on this, the page is displayed in one form or another.

In the session, you can not only indicate the fact of authorization, but also record some user data to display on the page, for example, a name or nickname. The decision about whether to use sessions or cookies is made on a site-by-site basis. If the site contains important information, then it is better to use sessions, because it is much more difficult to find out someone else’s registration data.

Authorization and registration forms

The authorization form is usually located on the main page, or it can be on all pages of the site. Basically, a separate page is created for the registration form. We will create just one page, which will contain both forms, and the user data will be displayed on it. For now it will only contain HTML code, but we will immediately create a PHP file, because in the future it will be a script. Let's call it formreg.php. The page code will be like this:

formreg.php:

Registration

We will record user registration data in the users table. If you do not have such a table yet, then create it. It should contain the fields id, login and pas. We will not use other fields. If they are in the table, they will remain empty.

registration.php:

3
4
5
6
7
8
9
10

$login=$_POST["login"]; $pas=$_POST["password"]; $db=mysqli_connect("localhost", "root", "", "mybase"); $query="INSERT INTO users (login, pas) VALUES ("$login", "$pas""); $result=mysqli_query($db, $query); if ($result) header("Location: formreg.php"); mysqli_close($db);

On line 9 we set it to return to the forms page. Since the execution of the script and reloading of the page occurs very quickly on the local server, visually it will look as if nothing happens when you click the “Register” button. On real sites, they usually go to a special page with information that the user is registered and registration data. Try logging and see if new entries appear in the database.

Authorization

The authorization form runs the authorization.php file on the server. This script takes a login and primary role and checks whether such a user exists. If there is, then the login will be recorded in the session. If such a user is not found, information about this will be recorded in the session. This is necessary so that the page that will be opened after executing the script receives this information and displays a message that an incorrect login or password has been entered. The script code is like this:

authorization.php:

3
4
5
6
7
8
9
10
11
12
13
14

session_start(); $login=$_POST["login"]; $pas=$_POST["password"]; $db=mysqli_connect("localhost", "root", "", "mybase"); $query="SELECT * FROM users WHERE login="$login" AND BINARY pas="$pas""; $result=mysqli_query($db, $query); if (mysqli_num_rows($result)) $_SESSION["login"]=$login; else $_SESSION["login"]="er login"; header("Location: formreg.php"); mysqli_close($db);

In line 7, a request is generated to select a line with the login and password received from the form. The keyword BINARY is written before the pas field. It is needed so that when comparing using this field, the case of characters is taken into account. If you need the case to be taken into account when comparing the login, then BINARY needs to be written before it. The example makes a request to select all fields. In practice, you can select only those fields whose data will need to be displayed on the page.

After receiving the result, it is checked whether the specified record is found. If there is a record, then the login is recorded in the session. If the user is not found, then the string “er login” is written instead of the login. You can write a different text, but you need to be sure that it will not match any login. Then you return to the page with forms.

The site pages must contain code that checks whether there is a login in the session. And depending on this, it is determined how the page should look. In our example there is only one page. We'll do a test on it. Only the code will be divided into two parts. The session must be opened before any data is output, that is, before the HTML code. Therefore, this part is located at the very beginning of the page. And the rest of the code is inside the tag , because it adds content to the page. Add the following line to the top of the page:

If there is a login in the session, but it contains the line “er login”, then a message is displayed that the login or password is incorrect. After the message is displayed, the login becomes empty. This is done so that the message is displayed only once and does not appear when moving to other pages. If the login is different, then the user is authorized and the page is generated as for registered users. If there is no login, then there has been no authorization yet and the page is displayed for unregistered users.

We have considered only the general principle of creating a registration and authorization function. On real sites it is more complicated. Forms should only be displayed to unauthorized users. In addition, you need to add a "Logout" button, which cancels authorization. When registering, you need to check the form, check the uniqueness of the login and add password confirmation.







2024 gtavrl.ru.