How to Create a Login System in PHP & MySQLi?

If you are working on a web development project where users can register and login then you must create a secure login system for your website so that you can allow users to login to your website without any hassle. We can create a login system in PHP very easily, and we’ll need to have a MySQLi database and table in order to save the user information such as user name, user email and user password etc. After we have a table to store users then we can create a script in PHP for verifying the users who want to sign in to our website. Let’s do it in PHP.


Create the Table for Users

The first step for creating such system in PHP is to create a database inside PHPMyAdmin and after you create a database with the name “users”,  after that simply create a new table named “users” in that database & add only 4 columns. You can give the following names to your table’s columns:

  • user_id
  • user_name
  • user_email
  • user_password

After creating the table & adding the column names, simply find the “Insert Option” there, and insert two or three test users to that table. When you complete this task, then you can create a simple sign in form to verify the users and let them sign in to our main page of the website.

Watch this video tutorial first!

Create the Login Script in PHP

When we create a registration form, we may ask users to enter their full details such as name, email, password, country, date of birth etc, but when we create the login form, we only need two things, either user name & password or email & password. So here we’ll create a simple HTML form for user_email and user_password, and after the user enters their details, we’ll look into our table, if his/her details are existing, we’ll send them to the main page, else we’ll give them an error in php. The HTML login form will be something like this:

<!DOCTYPE html><?php session_start();?>



<title>User Login</title>



<form action=”login.php” method=”post”>

<table width=”500″ align=”center” bgcolor=”skyblue”>

<tr align=”center”>

<td colspan=”3″><h2>User Login</h2></td>



<td align=”right”><b>Email</b></td>

<td><input type=”text” name=”email” required=”required “/></td>



<td align=”right”><b>Password:</b></td>

<td><input type=”password” name=”pass” required=”required></td>


<tr align=”center”>

<td colspan=”3″>

<input type=”submit” name=”login” value=”Login”/>







Using the above simple HTML form, we’ll get the user email and user password, we’ve given the appropriate names to the <input> tags which we can target in PHP using the $_POST method, so we’ll get the values from the <input> fields and then we’ll check whether we have that user in the database or not, so after validation, if the user is existing, we’ll allow them to enter the site, else we’ll add an error in PHP.

The PHP script for this login system will be something like this:


// establishing the MySQLi connection


$con = mysqli_connect(“localhost”,”root”,””,”users”);

if (mysqli_connect_errno())


echo “MySQLi Connection was not established: ” . mysqli_connect_error();


// checking the user


$email = mysqli_real_escape_string($con,$_POST[’email’]);

$pass = mysqli_real_escape_string($con,$_POST[‘pass’]);

$sel_user = “select * from users where user_email=’$email’ AND user_pass=’$pass'”;

$run_user = mysqli_query($con, $sel_user);

$check_user = mysqli_num_rows($run_user);



echo “<script>‘home.php’,’_self’)</script>”;


else {

echo “<script>alert(‘Email or password is not correct, try again!’)</script>”;





In the simple PHP script above, we first established a connection to the database using mysqli_connect, and after that we used if(isset($_POST[‘login’])) to check whether the login button is pressed/active or not, in case that is clicked then we just got the values from the <input> types>name>email and we passed these values to local variables in PHP > $email > $pass. After we have the entered values, we can validate them by checking the table, and we did that by running a query and check both user_email and user_password, if that query finds the records in the table, we send the user to “home.php” which is a welcome page, but if the user has entered wrong details then we’ve added an error in JavaScript. Furthermore, we’ve added “mysqli_real_escape_string()” function to both email & password, so that someone cannot attack our database, and it will escape if there is something unknown data coming in the form, so this way, we’ll secure the login form.

Additionally, we’ll can use $_SESSION Array in PHP to end of the session of the user when they want to logout from our website. so you must add a session_start() in the starting of the HTML page which I’ve done in the login page. This will store the user session if the user has logged in successfully. I’ve registered the session of the user if the login is successful, you can find $_SESSION[‘user_email’]=$email in the PHP code above, that will create a new session for the user and every user will have a new session automatically.

Creating the Logout PHP Script

Now after the user is logged in, you can simply add a “Logout” link to the welcome page, and when a user clicks that link, he/she will be redirected to logout.php, and logout.php script will be something like this:




echo “<script>‘login.php’,’_self’)</script>”;


So the above simple logout page will destory or end up the session of the user, and will redirect him/her to the login.php where they’ll have to enter their details again if they want to login again same as Facebook.

It’s end up here, if you have questions then do let me know in the comments, I’ll be glad to help you out!

About Abdul Wali

Abdul Wali is a professional blogger, marketer and web developer working online for last 5 years, he's been deeply involved in PHP, Web Development, SEO and computer video tutorials in different languages i.e English, Urdu and Pashto. You can catch him on and add him on Facebook.

Check Also


Best Websites to Buy PHP Scripts & Themes

PHP is a powerful web development language and many popular platforms are built with PHP ...

  • Michael Desmadril

    Looks decent and fine but what if the user goes to home.php straight away? How do you secure your pages…it seems like you can pass the login here…

    Also, why not use prepared statements? ….it is Mysqli….

    Anyhow, basic and simple explained! TYVM!

    • Hi Michael,
      Thanks for stepping by here, pages can be secured with different methods, but this was the basic understanding with practical step to create a simple login system in PHP/MySQLi.

  • Parsa Soroori

    Thank you. There is something wrong in your code. We have to create a column named user_pass in the table and not user_password

    • You welcome, that’s typo, so you can correct it!

  • Isa Chavez Cervantes

    Thanks so much Wali!!! you are the best!! Im sooooo happy now! I wasted my time like 4 hours and you solve my issues in minutes! Love U!!!

    • hmm, that’s great to know, thanks for liking!

  • Samee Ur-Rehman

    can you added me in skype please i really like to have conversation with you becoz i got some errors i wanted to show you ( im making my server user controll panel and im new to php ,mysqli, html ,css ) i hope you can understand me ( SKYPE: sami.nizamani )

  • ajax php mysqli login script

    where is the video link please upload it ..

  • rexpurve

    nice tutorial , i was able to learn and build just because of this tutorial. thanks

    • it’s great to hear that this tutorial helped you!

  • Ijaz Sunny

    sir.! have you made video tutorials on Android..?

  • Rodrigo Schneider Wernke

    Hello! Thanks for your tutorial, the only script that helped me. Just for know, how I can do a code to avoid users to access specific page, only if they are logged in? Example, I have the page ‘admin.php’, using the form to login your script will redirect to it, but if the users try to went to this page just changing the URL they can.

    • Hello, you welcome!
      You can use this code to prevent user from accessing that page, below is the example:

      header(“location: login.php”);
      else {

      All html or any admin code goes here…..

      ?php } ?

      Please put the starting and closing brackets of php.

      • Rodrigo Schneider Wernke

        Hi friend. Thanks again for your help, it worked here, now I can’t access the page without logging in. But, even if I log in (typing the user and pass at form) it doesn’t work. How can I send you the code for analysis?

        • Louise

          did you manage to resolve this issue? as I am now experiencing the same problem and its driving me crazy!! many thanks

      • Louise

        how did you get this to work? I just get syntax errors and unexplained >

      • Louise

        Hi, As per above even if user enters actual user name and password being directed to log in page can you help please?

  • kehulum belay

    am new for php/mesqli but your codes are good.

    • hi, that’s great to hear from you about my codes.

  • Darlington Emeh

    hello, am Darlington. am kinda new into PHP. Pls, i neeeeeeed help here. i have tried using your format for creating a login page, its returning a blank page when i click login whether username or password is entered or not.

    below is the my form:

    Request Form

    Only Authorized Login!!

    Note that my database name is ‘quotation_db’ with a table called ‘users’. the table has just 3fields—–id,myusername,mypassword.

    The next lines of codes is my checklogin page that will redirect successful login details into another page called ‘echorequest1.php’. Kindly help to correct the problem plssssss. find the checklogin script below:



    echo “‘echorequest1.php’,’_self’)”;


    else {

    echo “alert(‘usename or password is not correct, try again!’)”;





  • Doubting Thomas

    Hi I am getting an error here, I copied your code to see it working and I get an error on the echo link that says :-

    Parse error: syntax error, unexpected ‘>’ in C:wampwwwLogin.php on line 28 the code is as follows



    echo “‘home.php’,’_self’)”;


    echo “alert(‘Email or password is not correct, try again!’)”;


    it suggests that there is a bad > symbol but I can’t see it can you please ?

    • Dheeraj Singh

      plz check Dis symbol ‘ ‘ ……


    Hi Sir ,
    Your posted 29 videos for php and mysql for E-Commerce site(myshop)..Your videos are simply superb and understandable…In that videos you are not expained Login and My account ..In your videos your given link onlinetuting/myshop it is not working..How can I get the complete project of E-Commerce site(myshop)…please kindly provide that project….

  • Dheeraj Singh

    ” ” plz check dis sign …somewhere this is mising

  • Sarathi B

    It s working Perfect. Thank you so much

  • Louise

    HI, i have been trying for days to get my log in page to work but have to say yours is much cleaner then any attempts of mine!!
    I am having an issue that code is reaching last else tag and opening view.php.
    Have you any idea??? 🙁
    this is my code:

    header(‘Location: ../adminmain.php’);
    else {
    header(‘Location: ../view.php’);

    • Louise

      really do not know why my code will not fully show!! not having a good day please let me know if you can’t access this code and if I am doing something wrong, I just pasted code in

      • Louise

        got it to work!! great code literally looked for two days and could not make head or tail or other code as just learning php for dissertation.

        THANK YOU!

    • Meshileya Israel

      why not type the full code…since i can’t see the condition of your if statement

  • satish

    sir how to make user password forget system please tell me full process of them

  • Mehdi

    Hi sir, thank you for the tutorial it’s very clear. But I have a little problem. I want to do a If statement where if the user “admin” connects then we redirect him to a page for the admin, and if all other users conncects then we redirect them to a page for the visitors. I tried but I can’t found the code, can you help me please ? Thank a lot.

  • Sukron Hidayatullah

    It’s a combination of articles and a great tutorial videos
    Thanks sir

  • satish

    Sir to register use with pass and email compare and check email in already available and most important is password hashing with registration.

  • Abhradeep Banerjee

    the video is no longer there…

  • Cody Eagleson

    not getting a submit button or it working is it suppose to be login.html, login.php and logout.php