If you need to make one of the sections of your site available to a limited but indefinite 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 will talk about the case when PHP sessions are used.

Perhaps you would like to see more modern way creating such a form. I still have plans for its complete modern and up-to-date presentation, but you can see that the form feedback can be built using object-oriented tricks in PHP.

To begin with, let's discuss all the steps that we will take next. What do we really 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 DBMS connection script. All the work we will perform 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;
  • secure 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 execute 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 the same directory):

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

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

User authorization

register.

Now our form needs to be given some form. At the same time, we will define rules for other elements. I, looking ahead, will give 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 may have noticed that PHP variables are present in the HTML code. They are the content of form text field attributes, the content of error containers. But we have not initialized these variables. Let's do that.

User Registration

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

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

We need the login and password fields to be non-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 should be terminated, an appropriate alert should be written to the array of error messages, and it should be displayed to the user. For the convenience of the user, we will save the login entered by him (if he specified it), writing its value to the $fields array.

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

Now, let's say the user clicked on the registration button, did not fill out the form fields. According to our algorithm, login and password cannot be empty. If this condition is not met, registration is not possible. We keep in mind that form data processing happens in the current scenario. So we need to change its code by adding the appropriate checks. Let us immediately discuss the following checks. If both login and password are entered, you need to check their compliance with the specified requirements. To check the login and password, we will create user 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 there is no login string, return an error message if(!$str) ( $error = " You didn't enter a username"; return $error; ) /** * Checking the username using regular expressions * Login must be no shorter than 4, no longer than 16 characters * It must contain Latin characters, numbers, * it can be 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 true return true; ) // Check user password function checkPassword($str) ( // Initialize variable with possible error message $error = ""; // If missing input string with login, return error message if(!$str) ( $error = "You didn't 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 can contain characters "_", "!", " (", ")" */ $pattern = "/^[_!)(.a-z\d](6,16)$/i"; $result = preg_match($pattern, $str); // If check failed, return error message if(!$result) ( $error = "Invalid characters in user password or password too short (long)"; return $error; ) // If everything is fine, return true return true; )

Now we need to modify the registration.php file to use the functions we declared. We'll add a condition to the script that checks for the registration button being clicked. Inside this condition, login and password checking is started. If any of the checks fail, we re-render the form and display an error message. If there are no errors, we register the user, while the registration form is no longer displayed, inform the user about successful registration, and use the header() function to 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 via a direct link.

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

You should have noticed one more new function in the script - registration() . 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 string, 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() ; // Write a query string $sql = "SELECT `id` FROM `users` WHERE `login`="" . $login . """; // Make a database query $query = mysql_query($sql) or die( ""); // 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 it // Write the 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 OK, 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 no parameter is specified in its action attribute, the data submitted by the form will be processed in the same script. So we need to write the code for processing, and add it to the login.php document.

User authorization

;">

If you are not registered in the system, please register.

You may have noticed that we now have another unfamiliar function in the authorization script — authorization() . This function should authorize the user by first checking if there is a registered user in the database with the same login and password. If such a user is not found, authorization will be aborted and a failure message will be displayed on the screen. Upon successful verification, the authorization() function will start the session and write the user's login and password values ​​into it, inform the script about the success of the authorization, and the script will redirect the user to a secure resource page.

/** * User authorization function. * Authorization of users 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 string, 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 there is such a user among the registered // Compose the 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 // To do this, we use the superglobal array $_SESSION $_SESSION["login"] = $login; $_SESSION["password"] = $password; / / Don't forget to close the database connection mysql_close(); // Return true to report successful user authorization return true; )

When a user enters a secure page, you should check the correctness of his authorization data. To do this, we need one more user-defined 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 authorization page.

Function checkAuth($login, $password) ( // If there is no login or password, return false if(!$login || !$password) return false; // Check if such user is registered // Connect to the DBMS connect(); // Compose the 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 landed on a secure page, we need to call the authorization data validation function. We will place the call and check script in a separate checkAuth.php file and connect it to those pages that will be closed for public access.

/** * Script for checking user authorization */ // Start the session, from which we will extract the login and password // of authorized users session_start(); // Include a file with custom functions require_once("functions.php"); /** * To determine if a user is logged in, we need * to check if records exist in the database for their username * and password. To do this, we will use the custom function * to check the correctness of the data of the authorized user. * 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 validation of existing data fails if(!checkAuth($_SESSION["login"], $_SESSION["password"])) ( // Redirect the user to the login page header("location: login.php"); // Terminate the execution of the script exit; ) ) // If there is no data either about the login or the user's password, // we consider that there is no authorization, redirect the user // to the authorization page else ( header("location: login.php"); // Stop script execution exit; )

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

Authorization and registration of users

Successful authorization.

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

As you can see, in the protected document we include only one file - checkAuth.php. All other files are included in other scenarios. Therefore, our code does not look bulky. We have 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 are * authorized through sessions, their username 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"] arrays, * 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 script for registration, authorization and verification of users is ready. You can use it for yourself, supplement, modify to suit your needs. If you have questions, you can ask them in the comments. You can download all the files discussed here, packed into one archive.

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

As part of the Personal Web Server service, sites hosted on an account can be launched not only on the main web server, but also on their own instance of the Apache web server, whose processes are always ready to process requests to the site.

In addition to optimizing request processing, a personal web server allows you to use software that is not available on a common web server: PHP accelerators, a comprehensive solution for improving the performance of projects under the control of the 1C-Bitrix CMS, and a PHP script debugging tool.

The service is available for use on all current tariff plans, you can connect it in the "Web Server" section of the Hosting Control Panel.

Principle of operation


The hosting technical site has a two-level web server configuration. The common Apache web server, having received a request from Nginx, is forced to create a new child process and terminate it when the request is processed.

A personal web server greatly simplifies the interaction of an account with the main Apache process: a certain number of personal web server processes are always running under the hosting account username, which have only two states: “busy” or “free”.

The processes of a personal web server are engaged in processing requests to the site in the amount determined by the selected tariff plan. You can see how the personal web server process receives and executes a request, and then is released, by yourself using the top utility in the console when connecting to a hosting account via SSH.

Capabilities

  • Running the Apache web server with additional modules that are not available on regular shared hosting accounts.
  • Restarting the Personal Web Server from the Control Panel.
  • Using PHP accelerators that significantly speed up the work of various CMS: Zend OPCache, APC , xCache and eAccelerator .
  • PHP extension management: Zend Optimizer , ionCube Loader , xDebug .
  • Optimization of projects under the control of CMS 1C-Bitrix by setting up a PHP environment that meets the requirements of the CMS.
  • Better performance than a generic web server by having request processes running all the time.

We recommend using the "Personal Web Server" service when hosting serious projects with medium and high traffic, or projects that require non-standard environment settings and advanced site administration capabilities.

Web server version control

PHP

PHP (Hypertext Preprocessor)- the most famous and widespread web application development language. The PHP version is set through personal web server management (available from 5.2 to 7.1 inclusive). The recommended PHP version that meets the requirements of most CMS and extensions is PHP 5.6. The list of current versions is updated in a timely manner.

uWSGI (Python)

WSGI (Web Server Gateway Interface) is a popular standard for interfacing between a Python program running on the server side and the Apache web server itself. Required for projects written in Python.

Node.js

Node.js- a software platform for executing JavaScript code. Node.js allows JavaScript to interact with devices through its API, connect external libraries in different languages ​​and provide calls to them from JavaScript code.

Using PHP Accelerators

PHP accelerators are extensions that store compiled PHP script code in memory for fast execution the next time it is called. They allow you to significantly speed up the execution of PHP scripts and reduce the resources of the web server required for this (according to some estimates - by 5-20 times).

In the normal way PHP works, each script must be compiled into machine code before execution and only then run. Compilation occurs each time the script is accessed, that is, each time the page is displayed, the compilation of the script starts again. It takes time and CPU resources to compile the script. PHP accelerators store the compiled version of the script in RAM. Thus, on subsequent calls to the script, compilation is not required, and PHP immediately starts executing the machine code. Caching saves CPU resources and reduces the time it takes to render a page.

In addition to the main function - script caching - accelerators also provide scripts with the ability to store arbitrary variables in RAM for later quick access. Page caching mechanisms in many content management systems (CMS) are based on this feature, which significantly speeds up their work.

When using a personal web server, four accelerators are available that provide caching of PHP scripts.

Zend OPCache

Zend OPCache- speeds up the work of sites in the PHP language by using the technique of caching compiled scripts (opcode) in RAM and applying additional optimizations. Testing the use of this accelerator showed the most optimal results for most CMS in conjunction with PHP 5.6.

APC

APC (Alternative PHP Cache)- open source software for caching the result of PHP scripts. It is recommended to use the APC cacher to improve the performance of sites created on popular CMS such as Joomla, WordPress, Drupal, UMI.CMS. PHP 5.6 and 7.0 support APCu and APCu-bc accelerator modules.

eAccelerator

eAccelerator- performs the functions of an accelerator, optimizer and unpacker and has built-in dynamic content caching functions. According to the results of testing conducted with representatives of CMS manufacturers, eAccelerator is recommended for use with the CMS "1C-Bitrix: Site Management" and the popular HostCMS.

xCache

xCache- effective for high-load projects. The xCache accelerator is only available when using CMS whose manufacturers recommend it.

Enabling the accelerator implies that the account consumes an additional memory area intended for data caching. The amount of memory available for use is determined by the tariff plan and is indicated in the relevant section of the site.

PHP modules and extensions

ZendOptimizer

Zend Optimizer- an application from Zend Technologies Ltd. The Zend Optimizer extension is a server-side module that is used to run scripts encoded with Zend Encoder and Zend SafeGuard Suite, significantly increasing their speed. Only available for PHP 5.2.

ionCube Loader

ionCube Loader- software required to decode source code encoded using ionCube Encoder technology. In total, the ionCube set of utilities (Encoder and Loader) allows you to encode, obfuscate and license PHP source code.

xDebug

xdebug- Open source software needed by experienced developers to debug site scripts. The inclusion of the resource-intensive xDebug utility implements the possibility of logging, in which all actions will be recorded, from accessing the site from the browser to receiving the finished page: executing internal scripts, generating SQL queries, accessing the site to third-party resources, etc.

Optimization for "1C-Bitrix"

The popular content management system "1C-Bitrix" has a number of system requirements for the hosting platform, including the setting of multibyte strings, which on modern versions of PHP must be changed only through the php.ini file. Both experienced developers and novice users will be able to configure the mbstring.func_overload function overload mechanism and the supported mbstring.internal_encoding character encoding by selecting the required version in the 1C-Bitrix Optimization list.

As a result of testing the performance of the site under the control of 1C-Bitrix, the best results were achieved when using the recommended caching using the ZendOPCache accelerator in conjunction with PHP 5.6.

For the settings to take effect, you must apply the desired setting and restart the Personal Web Server.

Trackbacks (0)

Updated on: 2018-03-12

Posted on: 2016-12-21

Over time PHP has been adding features that promote the development of secure applications, as well deprecated or removed features that made it easy to write insecure code.

Read this tutorial to learn how to create a modern login and registration system that takes advantage of PHP security-focused features and uses jQuery to send AJAX requests and Bootstrap to provide a fast and nice user interface that can work regardless if you use other frameworks or not.



If you have questions or comments you can post a message as a comment to this article or in its .

Change Log

2017-03-27: Added more download and install information using the composer tool.

2017-01-01: Updated the article to reflect that these continue to be secure practices in 2017




You need to be a registered user or login to post a comment

Login Immediately with your account on:

Good day friends! Let's take a look at user registration in PHP. First, let's define the conditions for our user registration:

  • The password is encrypted using an algorithm MD5
  • The password will be "salt"
  • Login busy check
  • User activation by letter.
  • Recording and storage of data in DBMS MySQL

To write this script, we need to understand what user registration is. User registration is the receipt of real user data, processing and storage of data.

In simple words, registration is just a record and storage of certain data by which we can authorize the user in our case - this is the Login and Password.

Authorization - granting a certain person or group of persons the rights to perform certain actions, as well as the process of verifying these rights when trying to perform these actions. Simply put, with the help of authorization, we can restrict access to a particular content on our site.

Let's take a look at the script directory structure to implement our login with authorization. We need to break scripts into logical parts. We placed registration and authorization modules in a separate directory. We will also place the connection to the database in separate directories. MySQL, file with custom functions, style file css and our template HTML. This structure allows you to quickly navigate through scripts. Imagine that you have a big site with a bunch of modules and so on. and if there is no order, it will be very difficult to find something in such a mess.

Since we will store all data in DBMS MySQL, then let's create a small table in which we will store registration data.

First you need to create a table in the database. Let's call the table bez_reg where bez is the table prefix, and reg table name.

Table structure: bez_reg

-- -- `bez_reg` table structure -- CREATE TABLE IF NOT EXISTS `bez_reg` (`id` int(11) NOT NULL AUTO_INCREMENT, `login` varchar(200) NOT NULL, `pass` varchar(32) NOT NULL , `salt` varchar(32) NOT NULL, `active_hex` varchar(32) NOT NULL, `status` int(1) NOT NULL, PRIMARY KEY (`id`)) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;

Now let's create the main scripts for further work.

INDEX.PHP FILE

CONFIG.PHP FILE

"); ?>

File 404.HTML

Error 404

Error 404

There was a 404 error on the page

Return

BD.PHP file

INDEX.HTML FILE

PHP MySQL user registration with activation email

FUNCT.PHP FILE

"."\n"; if(is_array($data)) ( foreach($data as $val) $err .= "

  • ".$val."
  • "."\n"; ) else $err .= "
  • ".$data."
  • "."\n"; $err .= ""."\n"; return $err; ) /**Simple MySQL query wrapper * @param string $sql */ function mysqlQuery($sql) ( $res = mysql_query($sql); /* Check result This is shows the actual query sent to MySQL as well as the error.*/ if(!$res) ( $message = "Bad query: " . mysql_error() . "\n"; $message .= "Entire query : " . $sql; die($message); ) return $res; ) /**Simple salt generator * @param string $sql */ function salt() ( $salt = substr(md5(uniqid()), - 8); return $salt; )

    Let's start writing registration. First, we will need to make a registration form template so that the user can enter his data for processing. Next, we will need to write the form handler itself, which will check the entered user data for correctness. After the data is successfully verified, we write it to our database and send an email to the user to activate his account.

    REG.PHP FILE

    You have successfully registered! Please activate your account!!"; //Activate the account if(isset($_GET["key"])) ( //Check the key $sql = "SELECT * FROM `". BEZ_DBPREFIX ."reg` WHERE `active_hex` = "". escape_str( $_GET["key"]) ."""; $res = mysqlQuery($sql); if(mysql_num_rows($res) == 0) $err = "Activation key is invalid!"; //Check for errors and display to the user if(count($err) > 0) echo showErrorMessage($err); else ( //Get the user's address $row = mysql_fetch_assoc($res); $email = $row["login"]; //Activate the account user $sql = "UPDATE `".BEZ_DBPREFIX ."reg` SET `status` = 1 WHERE `login` = "".$email ."""; $res = mysqlQuery($sql); //Send activation email $title = "(!LANG:Your account at http://website has been successfully activated"; $message = "Поздравляю Вас, Ваш аккаунт на http://сайт успешно активирован"; sendMessageMail($email, BEZ_MAIL_AUTOR, $title, $message); /*Перенаправляем пользователя на нужную нам страницу*/ header("Location:". BEZ_HOST ."less/reg/?mode=reg&active=ok"); exit; } } /*Если нажата кнопка на регистрацию, начинаем проверку*/ if(isset($_POST["submit"])) { //Утюжим пришедшие данные if(empty($_POST["email"])) $err = "Поле Email не может быть пустым!"; else { if(!preg_match("/^!} [email protected](+\.)+(2,6)$/i", $_POST["email"])) $err = "Email entered incorrectly"."\n"; ) if(empty($_POST[ "pass"])) $err = "Password field cannot be empty"; if(empty($_POST["pass2"])) $err = "Password confirmation field cannot be empty"; //Check for errors and display to the user if(count($err) > 0) echo showErrorMessage($err); else ( /*We continue to check the entered data Check for matching passwords*/ if($_POST["pass"] != $_POST["pass2" ]) $err = "Passwords do not match"; //Check for errors and display to the user if(count($err) > 0) echo showErrorMessage($err); else ( /*Check if we have such a user in the database* / $sql = "SELECT `login` FROM `".BEZ_DBPREFIX ."reg` WHERE `login` = "".escape_str($_POST["email"]) ."""; $res = mysqlQuery($sql); if(mysql_num_rows($res) > 0) $err = "Sorry Login: ". $_POST["email"] ." busy!"; //Check for errors and display to the user if(count($err) > 0) echo showErrorMessage($err); else ( //Get the HASH of the salt $salt = salt(); //Salt the password $pass = md5(md5($_POST["pass"]).$salt); /*If all goes well, write data to the database*/ $sql = "INSERT INTO `". BEZ_DBPREFIX ."reg` VALUES("", "" .escape_str($_POST["email"]) ."", "". $pass ."", "". $salt ."", "". md5($salt) ."", 0)"; $ res = mysqlQuery($sql); //Send activation email $url = BEZ_HOST ."less/reg/?mode=reg&key=". md5($salt); $title = "(!LANG:Registration on http:/ /website"; $message = "Для активации Вашего акаунта пройдите по ссылке ". $url .""; sendMessageMail($_POST["email"], BEZ_MAIL_AUTOR, $title, $message); //Сбрасываем параметры header("Location:". BEZ_HOST ."less/reg/?mode=reg&status=ok"); exit; } } } } ?>!}

    REG_FORM.HTML FILE

    PHP MySQL user registration with activation email

    Email *:
    Password *:
    Password confirmation *:

    Fields with an icon * required

    Since our user registration is ready, it's time to write authorization. We will create a form for user authorization, then we will write an authorization form handler and, finally, we will make a script show.php which will show us whether we are authorized in the system or not.

    AUTH.PHP FILE

    0) echo showErrorMessage($err); else ( /*Create a fetch query from the database to authenticate the user*/ $sql = "SELECT * FROM `". BEZ_DBPREFIX ."reg` WHERE `login` = "". escape_str($_POST["email"]) ."" AND `status` = 1"; $res = mysqlQuery($sql); //If login matches, check password if(mysql_num_rows($res) > 0) ( //Get data from table $row = mysql_fetch_assoc( $res); if(md5(md5($_POST["pass"]).$row["salt"]) == $row["pass"]) ( $_SESSION["user"] = true; // Reset parameters header("Location:". BEZ_HOST ."less/reg/?mode=auth"); exit; ) else echo showErrorMessage("Wrong password!"); ) else echo showErrorMessage("Login ". $_POST["email"] ." not found!"); ) ) ?>

    For those who have the latest version of PHP, I post this script using PDO because extension MySQL is deprecated and has been removed from the new version of PHP. Download registration and authorization php mysql pdo

    The archive was updated on February 24, 2015.

    Attention: If you are using this script on a local server like DENWER,XAMPP, then you should not wait for letters to your mailbox. Letters are in the stub sendmail. AT Denver you can find them along the way Z:\tmp\!sendmail\ You can open these files in any email client.

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

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

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

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

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

    In my case it looks like this:

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

    We save bd.php.
    Excellent! We have a table in the database, a connection to it. Now you can start creating a page where users will leave their data.

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



    Registration


    Registration
















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



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


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

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

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


    Main page


    Main page











    Register



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

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

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

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

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

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

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

    Checked everything, it works fine!