Last Updated:

PHP + MySQL : Create registration and authorization System


Now on almost every site a new user is offered to create a personal account. To implement this, you need to set up a full-fledged authorization system, which can be created through PHP in conjunction with the MySQL database.

Why do we need an authorization system?

For the site owner, the ability to register users is a great opportunity to get data about them and provide additional opportunities in return.

Let's analyze the main advantages of having a registration system:

  • the site owner creates an active community with users. So he gets the opportunity to interact with them directly;
  • marketers will be able to get useful information from registered people, which will improve the product on request, learn the shortcomings. Also, this data can help to set up advertising campaigns in more detail;
  • the developer will be able to implement convenient functionality for users who have registered, since ordinary "guests" will not be able to have a permanent connection;
  • competent implementation of authorization on the site will allow a new user to store all useful information. So, when registering in an online store, a person will always have his basket or the "Favorites" section at hand.


However, not every site requires authorization. It can be excluded on landing pages and personal blocks.


Parsing the main model and documents

The basis of the registration system includes several steps:

  • account creation: registration of login and password;
  • authorization on the site: entering personal data that were used during registration;
  • A cookie that includes each user's unique identifier and hash.

All this can be represented in the form of a basic model:

  • user_id (int(000))
  • user_login (Qwerty)
  • user_password (12345qwerty)
  • user_hash (qwerty)
  • user_ip (default 0)

Server Setup: How to Choose

As a server, you can use any option: virtual or physical (this is especially convenient for the work of a small company, for example, online, store).

One of the most practical can be considered Xampp, as it is ideal for creating a registration system for a small site. Therefore, before you start working with the database, install it on your computer.

We make a PHP + MySQL registration system

Important: the instructions specify the option with the use of cookies. This will allow new users to log in once and not constantly enter a login. We do not take a password in a cookie, since when hacking the site (and this can happen), full access to the personal account can get to scammers.

Creating an object in MySQL

We recommend creating an object (data storage system) based on the MySQL service.

To do this, we form a small table to store future data:

Table name: site.test

user_id int(00) unsigned not null auto_increment,
user_login qwerty not null,
user_password 12345qwerty not null,
primary key (user_id)
engine = myisam
character set utf8
collate utf8_general_ci;

Then we try to add the first entry:

insert into test.users (user_login, user_password)
values (‘test’,’g67dbh983vi’)

That is: test — login, g67dbh983vi — password.

Processing the Registration Form

Next, you need to create a document: regist.php. This is the processing file of the registration form through which users will be able to access the personal account.

You need to enter the following code in it:

// New user
registration form // Connect to the database
$link=mysqli_connect ("localhost", "mysql_user", "mysql_password", "testtable");
{$err = [];
// perform a login check
{$err[] = "Login should consist of numbers, Latin letters: uppercase and lowercase, punctuation marks";}
if(strlen($_POST['login']) < 3 or strlen($_POST['login']) > 30)
{$err[] = "login length must be greater than 8 characters";}
// perform a duplicate login check on the site
$query = mysqli_query($link, "SELECT user_id FROM users WHERE user_login='".mysqli_real_escape_string($link, $_POST['login'])."'");
if(mysqli_num_rows($query) > 0)
{$err[] = "This login is already in use by another user";}
// No errors detected, register a new user, save information in the database
if(count($err) == 0)
{$login = $_POST['login'];
// Create a double hash and get rid of
extra spaces $password = md5(md5(trim($_POST['password'])));
mysqli_query($link,"INSERT INTO users SET user_login='".$login."', user_password='".$password."'");
header(«Location: login.php»); exit();}
{print "<b> Errors occurred while registering a new user:</b><br>";
foreach($err AS $error)
{print $error." <br>»;}
<form method="POST">
Login <input name="login" type="text" required><br>
Password <input name="password" type="password" required><br>
<input name="submit" type="submit" value="Login">

Configuring the Authorization System

Next, you need to create a login.html document that will be responsible for authorizing the user in the site system.

Importantly! The document has a parameter session_start (), which is needed to check whether the user was previously authorized.

// User
Authorization System // Generate a random
function generateCode($length=8)
{$chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHI JKLMNOPRQSTUVWXYZ0123456789 ><,./!&&;;
$code = «»;
$clen = strlen($chars) — 1;
while (strlen($code) < $length) {
$code .= $chars[mt_rand(0,$clen)];}
return $code;}
// Connect to the database
$link=mysqli_connect("localhost", "mysql_user", "mysql_password", "testtable");
// Search the database record that has a login that was entered by user
$query = mysqli_query($link,"SELECT user_id, user_password FROM users WHERE user_login='".mysqli_real_escape_string($link,$_POST['login'])."' LIMIT 1″);
$data = mysqli_fetch_assoc($query);
// Next, compare the entered password
if($data['user_password'] === md5(md5($_POST['password'])))
// Generate and encrypt a random number
of $hash = md5(generateCode(10));
// In the event that the user is bound to the IP address
// Translate his IP address
$insip = ", user_ip=INET_ATON('".$_SERVER['REMOTE_ADDR'].")";"
// Write in the database the hash of the new authorization and the IP address
of the mysqli_query($link, "UPDATE users SET user_hash='".$hash."' «.$insip.» WHERE user_id='».$data[‘user_id’].»‘»);
// Insert cookies
setcookie("id", $data['user_id'], time()+60*60*24*30, «/»);
setcookie(«hash», $hash, time()+60*60*24*30, «/», null, null, true); httponly !!!
// Next, redirect the browser to a new page, which is necessary to check the
header script ("Location: check.php"); exit();
{print "Login and password are not suitable. Try entering again";}
<form method="POST">
Login <input name="login" type="text" required><br>
Password <input name="password" type="password" required><br>
Bind to IP address (not recommended) <input type="checkbox" name="not_attach_ip"><br>
<input name="submit" type="submit" value="Login">

After that, we create a new document — check.php, in which the data validation script is prescribed:

// Check
// Connect to the database
$link=mysqli_connect("localhost", "mysql_user", "mysql_password", "testtable");
if (isset($_COOKIE[‘id’]) and isset($_COOKIE[‘hash’]))
{$query = mysqli_query($link, «SELECT *,INET_NTOA(user_ip) AS user_ip FROM users WHERE user_id = ‘».intval($_COOKIE[‘id’]).»‘ LIMIT 1″);
$userdata = mysqli_fetch_assoc($query);

if(($userdata[‘user_hash’] !== $_COOKIE[‘hash’]) or ($userdata[‘user_id’] !== $_COOKIE[‘id’])
or (($userdata[‘user_ip’] !== $_SERVER[‘REMOTE_ADDR’]) and ($userdata[‘user_ip’] !== «0»)))
{setcookie(«id», «», time() — 3600*24*30*12, «/»);
setcookie(«hash», «», time() — 3600*24*30*12, «/», null, null, true); // httponly !!!
print «Что-то пошло не так»;}
{print «Здравствуйте, «.$userdata[‘user_login’].». Система работает исправно!»;}
{print «Включите куки»;}

For additional protection of user data (for example, from password guessing systems by brute force), you can connect the input of captcha after the first input attempt or a delay in authorization.