Creating a simple user registration system in PHP and MySQL. Creating an Incredibly Simple Registration System in PHP and MySQL Cowardly users registration php

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.

You'd probably like to see a more modern way of creating this shape. I still have no plans to fully present it in a modern and relevant way, but you can see that the feedback form can be built using object-oriented techniques in PHP.

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 the 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 pressed. 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.

Hello! Now we will try to implement the simplest registration on the site using PHP + MySQL. To do this, Apache must be installed on your computer. The working principle of our script 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 are creating a database on your PC http://localhost/phpmyadmin/). Create a table users, it will have 3 fields.

I create it in the mysql database, you can create it in another database. Next, set the values ​​as in the 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 for this server","password for this server");
mysql_select_db ("name of the database we are connecting to", $db);
?>

In my case it looks like this:

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

Save bd.php.
Great! We have a table in the database and a connection to it. Now you can start creating a page on which users will leave their data.

3. Create a reg.php file with the contents (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 might 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 login you entered is already registered. Please enter another login.");
}
// if this is not the case, 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. Home page";
}
else(
echo "Error! You are not registered.";
}
?>

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

// the whole procedure works in sessions. It is where 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();
?>


Home page


Home page











Register



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

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

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

session_start();// the whole procedure works on sessions. It is where 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);) ) //enter the login entered by the user into $login variable, if it is empty, then destroy the variable
if (isset($_POST["password"])) ( $password=$_POST["password"]; if ($password =="") ( unset($password);) )
//put the user-entered password into the $password variable, if it is empty, then destroy the variable
if (empty($login) or empty($password)) //if the user did not enter a login or password, then we issue an error and stop the script
{
exit("You have not entered all the information, go back and fill out 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 might 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 must be in the same folder as all the others, if it is not then just change the path

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

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

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

I checked everything, it works properly!

Creating a membership based site seems like a daunting task at first. If you ever wanted to do this by yourself, then just gave up when you started to think how you are going to put it together using your PHP skills, then this article is for you. We are going to walk you through every aspect of creating a membership based site, with a secure members area protected by password.

The whole process consists of two big parts: user registration and user authentication. In the first part, we are going to cover creation of the registration form and storing the data in a MySQL database. In the second part, we will create the login form and use it to allow users access in the secure area.

Download the code

You can download the whole source code for the registration/login system from the link below:

Configuration & Upload
The ReadMe file contains detailed instructions.

Open the source\include\membersite_config.php file in a text editor and update the configuration. (Database login, your website’s name, your email address etc).

Upload the whole directory contents. Test the register.php by submitting the form.

The registration form

In order to create a user account, we need to gather a minimal amount of information from the user. We need his name, his email address and his desired username and password. Of course, we can ask for more information at this point, but a long form is always a turn-off. So let’s limit ourselves to just those fields.

Here is the registration form:

Register

So, we have text fields for name, email and the password. Note that we are using the for better usability.

Form validation

At this point it is a good idea to put some form validation code in place, so we make sure that we have all the data required to create the user account. We need to check if name and email, and password are filled in and that the email is in the proper format.

Handling the form submission

Now we have to handle the form data that is submitted.

Here is the sequence (see the file fg_membersite.php in the downloaded source):

function RegisterUser() ( if(!isset($_POST["submitted"])) ( return false; ) $formvars = array(); if(!$this->ValidateRegistrationSubmission()) ( return false; ) $this- >CollectRegistrationSubmission($formvars); if(!$this->SaveToDatabase($formvars)) ( return false; ) if(!$this->SendUserConfirmationEmail($formvars)) ( return false; ) $this->SendAdminIntimationEmail($ formvars); return true; )

First, we validate the form submission. Then we collect and ‘sanitize’ the form submission data (always do this before sending email, saving to database etc). The form submission is then saved to the database table. We send an email to the user requesting confirmation. Then we intimate the admin that a user has registered.

Saving the data in the database

Now that we gathered all the data, we need to store it into the database.
Here is how we save the form submission to the database.

function SaveToDatabase(&$formvars) ( if(!$this->DBLogin()) ( $this->HandleError("Database login failed!"); return false; ) if(!$this->Ensuretable()) ( return false; ) if(!$this->IsFieldUnique($formvars,"email")) ( $this->HandleError("This email is already registered"); return false; ) if(!$this->IsFieldUnique( $formvars,"username")) ( $this->HandleError("This UserName is already used. Please try another username"); return false; ) if(!$this->InsertIntoDB($formvars)) ( $this- >HandleError("Inserting to Database failed!"); return false; ) return true; )

Note that you have configured the Database login details in the membersite_config.php file. Most of the cases, you can use “localhost” for database host.
After logging in, we make sure that the table is existing.(If not, the script will create the required table).
Then we make sure that the username and email are unique. If it is not unique, we return error back to the user.

The database table structure

This is the table structure. The CreateTable() function in the fg_membersite.php file creates the table. Here is the code:

function CreateTable() ( $qry = "Create Table $this->tablename (". "id_user INT NOT NULL AUTO_INCREMENT ," "name VARCHAR(128) NOT NULL ," "email VARCHAR(64) NOT NULL ," " "phone_number VARCHAR(16) NOT NULL ," "username VARCHAR(16) NOT NULL ," "password VARCHAR(32) NOT NULL ," "confirmcode VARCHAR(32) ," "PRIMARY KEY (id_user)." ")"; if(!mysql_query($qry,$this->connection)) ( $this->HandleDBError("Error creating the table \nquery was\n $qry"); return false; ) return true; )

The id_user field will contain the unique id of the user, and is also the primary key of the table. Notice that we allow 32 characters for the password field. We do this because, as an added security measure, we will store the password in the database encrypted using MD5. Please note that because MD5 is an one-way encryption method, we won’t be able to recover the password in case the user forgets it.

Inserting the registration to the table

Here is the code that we use to insert data into the database. We will have all our data available in the $formvars array.

function InsertIntoDB(&$formvars) ( $confirmcode = $this->MakeConfirmationMd5($formvars["email"]); $insert_query = "insert into ".$this->tablename."(name, email, username, password, confirmcode) values ​​("" . $this->SanitizeForSQL($formvars["name"]) . "", "" . $this->SanitizeForSQL($formvars["email"]) . "", "" . $ this->SanitizeForSQL($formvars["username"]) . "", "" . md5($formvars["password"]) . "", "" . $confirmcode . "")"; if(!mysql_query( $insert_query ,$this->connection)) ( $this->HandleDBError("Error inserting data to the table\nquery:$insert_query"); return false; ) return true; )

Notice that we use PHP function md5() to encrypt the password before inserting it into the database.
Also, we make the unique confirmation code from the user’s email address.

Sending emails

Now that we have the registration in our database, we will send a confirmation email to the user. The user has to click a link in the confirmation email to complete the registration process.

function SendUserConfirmationEmail(&$formvars) ( $mailer = new PHPMailer(); $mailer->CharSet = "utf-8"; $mailer->AddAddress($formvars["email"],$formvars["name"]) ; $mailer->Subject = "Your registration with ".$this->sitename; $mailer->From = $this->GetFromAddress(); $confirmcode = urlencode($this->MakeConfirmationMd5($formvars["email" ])); $confirm_url = $this->GetAbsoluteURLFolder()."/confirmreg.php?code=".$confirmcode; $mailer->Body ="Hello ".$formvars["name"]."\r\ n\r\n". "Thanks for your registration with ".$this->sitename."\r\n". "Please click the link below to confirm your registration.\r\n." "$confirm_url\r \n". "\r\n". "Regards,\r\n". "Webmaster\r\n". $this->sitename; if(!$mailer->Send()) ( $this-> HandleError("Failed sending registration confirmation email."); return false; ) return true; )

Updates

9th Jan 2012
Reset Password/Change Password features are added
The code is now shared at GitHub.

Welcome backUserFullName(); ?>!

License


The code is shared under LGPL license. You can freely use it on commercial or non-commercial websites.

No related posts.

Comments on this entry are closed.

Last modified on July 23rd, 2019 by Vincy.

User registration or sign up is an integral part of many web applications and it is critical to get it right for the success of the application. It is the starting point of user engagement with your application.

It should be as simple as possible with best UI / UX. Implementing user registration functionality using PHP is a simple task and I will walk you through the steps with example in this article.

What is inside?

How does this PHP user registration example work?

This example code can be separated into 3 parts.

  1. Getting user information via a HTML form.
  2. Validating user submitted information on form submit.
  3. Database handling to save registered user to the database after validation.

The third step will be executed after ensuring that the user is not added already. This data uniqueness validation will be performed based on their email and username entered by them.

During registration we generally collect user information, who are ready to register with our application. Some of them will be mandatory and some of them will be optional.

So, this functionality may also include validation part to ensure about the non-emptiness and the format of the user data. The validation could be done either in client-side or server side.

Having validation at server-side is always better. You can choose to have it in client-side also for the ease of use of the users. But having at the server-side is not optional and a minimum requirement.

File structure

HTML form to allow user to register

In this example, the registration form contains the fields Username, Name(Display Name), Password and Email. It also has the Confirm Password field to let the user to reenter his password for the confirmation. These two passwords will be compared later at the time of a .

By submitting this form, the user is expected to agree the terms and conditions. So a checkbox field is added before the Register button for ensuring it.

PHP User Registration Form

Sign Up
"; } ?>
">
">
">
I accept terms and conditions


And the styles are,

Body ( font-family: Arial; color: #333; font-size: 0.95em; ) .form-head ( color: #191919; font-weight: normal; font-weight: 400; margin: 0; text-align : center; font-size: 1.8em; ) .error-message ( padding: 7px 10px; background: #fff1f2; border: #ffd5da 1px solid; color: #d6001c; border-radius: 4px; margin: 30px 0px 10px 0px ; ). #ffffff; border-spacing: initial; margin: 15px auto; word-break: break-word; table-layout: auto; line-height: 1.8em; color: #333; border-radius: 4px; padding: 20px 40px ; width: 380px; border: 1px solid; border-color: #e5e6e9 #dfe0e4 #d0d1d5; ) .demo-table .label ( color: #888888; ) .demo-table .field-column ( padding: 15px 0px; ) .demo-input-box ( padding: 13px; border: #CCC 1px solid; border-radius: 4px; width: 100%; ) .btnRegister ( padding: 13px; background-color: #5d9cec; color: #f5f7fa; cursor: pointer; border-radius: 4px; width: 100%; border: #5791da 1px solid; font-size: 1.1em; ) .response-text ( max-width: 380px; font-size: 1.5em; text-align: center; background: #fff3de; padding: 42px; border-radius: 3px; border: #f5e9d4 1px solid; font-family : arial; line-height: 34px; margin: 15px auto; ) .terms ( margin-bottom: 5px; )

How to validate user information on form submit

A server-side form validation script is added in this example for validating the user registration data. This PHP validation script will be called on submitting the registration form.

This script validates all form fields to check the non-emptiness for each field. Then it validates the user email format using PHP filter_var() function.

As the registration includes password confirmation feature, the password comparison will take place at this part of this example.

Finally, the validation script will check if the user accepts term and condition by checking the appropriate box on the form.

Once all the validation completed by returning boolean true, then the actual registration process will take place.

Function validateMember() ( $valid = true; $errorMessage = array(); foreach ($_POST as $key => $value) ( ​​if (empty($_POST[$key])) ( $valid = false; ) ) if($valid == true) ( ​​if ($_POST["password"] != $_POST["confirm_password"]) ( $errorMessage = "Passwords should be the same."; $valid = false; ) if (! isset ($error_message)) ( if (! filter_var($_POST["userEmail"], FILTER_VALIDATE_EMAIL)) ( $errorMessage = "Invalid email address."; $valid = false; ) ) if (! isset($error_message)) ( if (! isset($_POST["terms"])) ( $errorMessage = "Accept terms and conditions."; $valid = false; ) ) ) else ( $errorMessage = "All fields are required."; ) if ( $valid == false) ( return $errorMessage; ) return; )

PHP MySQL code to access database to save registered user

Server-side user form validation

This is the PHP entry point to handle all the server-side script to validate form and to handle database operations based on the validation result.

validateMember($username, $displayName, $password, $email); if (empty($errorMessage)) ( $memberCount = $member->isMemberExists($username, $email); if ($memberCount == 0) ( $insertId = $member->insertMemberRecord($username, $displayName, $ password, $email); if (! empty($insertId)) ( header("Location: thankyou.php"); ) ) else ( $errorMessage = "User already exists."; ) ) ) ?>

Check if user already exists

The isMemberExists() function is used to check the user data uniqueness based on their email and the username. If the entered username or email there exists in the user database, then the registration process will be stopped by returning and acknowledgement.

This acknowledgement will notify that the “user already exists”. The code is

Function isMemberExists($username, $email) ( $query = "select * FROM registered_users WHERE user_name = ? OR email = ?"; $paramType = "ss"; $paramArray = array($username, $email); $memberCount = $this->ds->numRows($query, $paramType, $paramArray); return $memberCount; )

Insert member data to the database

If it returns 0 then it means that there is no such users exist with the email or the username entered. And so, the registration data will be inserted to the database. The following code shows the member insert method.

Function insertMemberRecord($username, $displayName, $password, $email) ( $passwordHash = md5($password); $query = "INSERT INTO registered_users (user_name, display_name, password, email) VALUES (?, ?, ?, ? )"; $paramType = "ssss"; $paramArray = array($username, $displayName, $passwordHash, $email); $insertId = $this->ds->insert($query, $paramType, $paramArray); return $insertId; )

DataSource.php

This is the generic data source class in PHP to perform database operations. It includes functions to connect database and execute various queries to get database result, row count, execute insert and more.

This datasource class is generic and kept as simple as possible. It is efficient and I use it in my most of the micro projects and tutorials. You are free to download and use it.

Important thing is never forget to use the Prepared Statements. It helps you to safeguard from SQL injection attacks and it is the first step in terms of implementing security in a web application.

conn = $this->getConnection(); ) /** * If connection object is needed use this method and get access to it. * Otherwise, use the below methods for insert / update / etc. * * @return \mysqli */ public function getConnection() ( $conn = new \mysqli(self::HOST, self::USERNAME, self::PASSWORD, self::DATABASENAME); if (mysqli_connect_errno()) ( trigger_error ("Problem with connecting to database."); ) $conn->set_charset("utf8"); return $conn; ) /** * To get database results * @param string $query * @param string $paramType * @ param array $paramArray * @return array */ public function select($query, $paramType="", $paramArray=array()) ( $stmt = $this->conn->prepare($query); if(! empty($paramType) && !empty($paramArray)) ( $this->bindQueryParams($sql, $paramType, $paramArray); ) $stmt->execute(); $result = $stmt->get_result(); if ($result->num_rows > 0) ( while ($row = $result->fetch_assoc()) ( $resultset = $row; ) ) if (! empty($resultset)) ( return $resultset; ) ) / ** * To insert * @param string $query * @param string $paramType * @param array $paramArray * @return int */ public function insert($query, $paramType, $paramArray) ( print $query; $stmt = $this->conn->prepare($query); $this->bindQueryParams($stmt, $paramType, $paramArray); $stmt->execute(); $insertId = $stmt->insert_id; return $insertId; ) /** * To execute query * @param string $query * @param string $paramType * @param array $paramArray */ public function execute($query, $paramType="", $paramArray=array()) ( $ stmt = $this->conn->prepare($query); if(!empty($paramType) && !empty($paramArray)) ( $this->bindQueryParams($stmt, $paramType="", $paramArray= array()); ) $stmt->execute(); ) /** * 1. Prepares parameter binding * 2. Bind parameters to the sql statement * @param string $stmt * @param string $paramType * @param array $ paramArray */ public function bindQueryParams($stmt, $paramType, $paramArray=array()) ( $paramValueReference = & $paramType; for ($i = 0; $i< count($paramArray); $i ++) { $paramValueReference = & $paramArray[$i]; } call_user_func_array(array($stmt, "bind_param"), $paramValueReference); } /** * To get database results * @param string $query * @param string $paramType * @param array $paramArray * @return array */ public function numRows($query, $paramType="", $paramArray=array()) { $stmt = $this->conn->prepare($query); if(!empty($paramType) && !empty($paramArray)) ( $this->bindQueryParams($stmt, $paramType, $paramArray); ) $stmt->execute(); $stmt->store_result(); $recordCount = $stmt->num_rows; return $recordCount; ) )

Database script

This database script has the create statement for the registered_users table. Import this script in your development environment to run this code.

Table structure for table `registered_users` -- CREATE TABLE IF NOT EXISTS `registered_users` (`id` int(8) NOT NULL AUTO_INCREMENT, `user_name` varchar(255) NOT NULL, `first_name` varchar(255) NOT NULL, ` last_name` varchar(255) NOT NULL, `password` varchar(25) NOT NULL, `email` varchar(55) NOT NULL, `gender` varchar(20) NOT NULL, PRIMARY KEY (`id`));

If the registration form validation fails, then the error message will be shown to the user as like as below.

Comments to “PHP User Registration Form (Sign up) with MySQL Database”

    Hi Vincy, I get the following errors when running the register code, please help.

    INSERT INTO registered_users (user_name, display_name, password, email) VALUES (?, ?, ?, ?)
    Warning: call_user_func_array() expects parameter 1 to be a valid callback, first array member is not a valid class name or object in C:\xampp\htdocs\PHP\JAMII-CASH\DataSource.php on line 136

    Fatal error: Uncaught Error: Call to a member function execute() on boolean in C:\xampp\htdocs\PHP\JAMII-CASH\DataSource.php:99 Stack trace: #0 C:\xampp\htdocs\PHP\JAMII -CASH\Member.php(83): Phppot\DataSource->insert('INSERT INTO reg…', 'ssss', Array) #1 C:\xampp\htdocs\PHP\JAMII-CASH\index.php(20 ): Phppot\Member->insertMemberRecord('chuki10', 'Ray', '202020', 'raf.yah.s.1@gma…') #2 (main) thrown in C:\xampp\htdocs\PHP\ JAMII-CASH\DataSource.php on line 99

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 on 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 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.