Simple User Registration & Login Script in PHP and MySQLi

Demo Download

Today i will share Simple User Registration & Login Script in PHP and MySQLi, i will explain the basic functionality of registration and access secured area. In this tutorial user can register, login to member secured area and logout.

Steps to Create Simple User Registration & Login Script in PHP and MySQLi

  1. Create a Database
  2. Create a Database Table with Following Five Fields:
    id, username, email, password, trn_date
  3. Create a Registration Form
  4. Create a Login Form
  5. Connect to the Database by using PHP
  6. Authenticate Logged in User
  7. Create Index Page
  8. Create Dashboard Page
  9. Create a Log Out
  10. Create a CSS File

1. Create a Database

To create a database, login to phpmyadmin and click on database tab, enter your database name and click on create database button or simply execute the below query. In my case i created database with the name register.

2. Creating a Database Table

To create table, execute the below query in SQL.

3. Creating a Registration Form

Simple create a page with name registration.php and paste the following code in it.

registration-php

4. Creating a Login Form

Create a page with name login.php and paste the following code in it.

login-php

5. Connect to the Database

Create a page with name db.php and paste the below code in it.

6. Authenticate Logged in User

Create a page with name auth.php and paste the below code in it.

7. Creating Index Page

Create a page with name index.php and paste the below code in it.

secured-area

8. Creating Dashboard Page

Create a page with name dashboard.php and paste the below code in it.

dashboard

9. Creating a Log Out

Create a page with name logout.php and paste the following code in it.

10. Creating a CSS File

Create a page with name style.css and paste the below code in it.

Note: In this tutorial CSS file is placed in css/style.css folder. So make sure that you also placed CSS file in the same css folder.

Click here to Insert, View, Edit and Delete Record from Database Using PHP and MySQLi

If you found this tutorial helpful so share it with your friends, developer groups and leave your comment.

Article By

Javed Ur Rehman is a passionate blogger and web developer, he loves to share web development tutorials and blogging tips. He usually writes about HTML, CSS, JavaScript, Jquery, Ajax, PHP and MySQL.

168 Comments

  1. I’ve been getting the following error when trying to register:
    Notice: Undefined variable: con in D:\xamp\htdocs\registration.php on line 21

    Warning: mysqli_real_escape_string() expects parameter 1 to be mysqli, null given in D:\xamp\htdocs\registration.php on line 21

    The lines are:
    <?php
    include 'db.php';
    // If form submitted, insert values into the database.
    if (isset($_REQUEST['username'])){
    $username = stripslashes($_REQUEST['username']); // removes backslashes
    $username = mysqli_real_escape_string($con,$username); //escapes special characters in a string

    (No modifications to your code)
    Could you help me, Javed?

    1. As you can see it is connection error, kindly make sure that your connection is established, $con variable is defined in db.php. Please enter your database credentials here to get connected with database, such as username, password, host. Check db.php file.

  2. Hi Javed nice eg for new in php.

    In your demo page invalid error show on same page on top login form but when i try its show error login page but not showing login form. Can you help me.

  3. I would like to know which part of the code that hide the password during the input ? Which part of the coding change the password input into **** during login and registration form. Thank you.

  4. Hi how would i add it so if i wanted a status on mine and say Admin and Members options and if your an admin if shows admin and if your not it shows no link?

    1. You can do this, all you need to do is check another check which you will create. for example create another column with name admin and INSERT 0 in that column if member is registering and 1 if Admin, normally we do not create admin through portal, we directly add admin from MySQL and enable registration option for members only.
      So to view file just check if user admin value is 0 or 1. If 1 then show files.

  5. Thanks for your tutorial. You code works fine. Keep up the good works. I added some other field to the form. I added First Name, Last Name and age. I want to fetch the whole of the data from the database from each row. This mean each data will be fetch from each column in a row. I want the result to display on index.php please what is the code i will add for this function and which page will i place the code? Thank you, God bless

  6. This is very usefull code thanks a lot. But i Have a problem if iam trying add a another field in registration form it shows black page please help me out from this

  7. hi, thanks for this tuto

    i’m in local
    i don’t understand something about password

    when u register, u write/choose ur own password
    but in the BDD, there is very complicate password… not the same i choose when i register

    so :
    this complicated password is sent to our email when i registered ??
    or, if is not this
    how can i add/replace MY own password in the BDD ??

    1. Adding password without encryption is not good practice, this also include the privacy of user, but if you just want to see the same password in db only for testing purpose, you can just remove md5() function from code.

  8. Solved the issue with replacing session_start() to ob_start() and put ob_flush() before last } … like

    //session_start();
    ob_start();
    require(‘../inc/conn.php’);
    include(‘include/siteRootAdmin.php’);

    and

    hope this will helpful to everybody facing the header issue. 🙂

  9. login.php not redirecting to index.php on server showing blank page, but it is working on localhost. what to do to make it work on server?

  10. Hello, i feel that i noticed you visited my weblog thus i came to go back the favor?.I am trying to find issues to improve my web site!I assume its adequate to use some of your ideas!!

  11. it is not working in my additional pages.
    it is working in only my home page.
    for example when i opened localhost/saghar then it worked correct but when i opend localhost/saghar/contact.php it does not worked. i gave it 4/5 stars because i knew solution for it.

  12. hi sir, thank you very much for your help/…every thing is work,but i can’t add another user,in registration…

    1. i downloaded the demo files but when i import it to my website it loads but when i try to sign in it says cant find database how do i create database with thedemo files i downloaded

  13. I’ve solved the issue everyone is having (after login). Here is how you fix it in 2 simple steps.

    Take the Login.php code and move the HTML part in the top down to below the php code. (Note: PHP code must be in the top in order for the redirect to work). Also, add your URL into the redirect URL line: (see below).

    <?php
    require('db.php');
    session_start();
    // If form submitted, insert values into the database.
    if (isset($_POST['username'])){
    // removes backslashes
    $username = stripslashes($_REQUEST['username']);
    //escapes special characters in a string
    $username = mysqli_real_escape_string($con,$username);
    $password = stripslashes($_REQUEST['password']);
    $password = mysqli_real_escape_string($con,$password);
    //Checking is user existing in the database or not
    $query = "SELECT * FROM users WHERE username='$username'
    and password='".md5($password)."'";
    $result = mysqli_query($con,$query) or die(mysql_error());
    $rows = mysqli_num_rows($result);
    if($rows==1){
    $_SESSION['username'] = $username;
    // Redirect user to index.php
    header("Location: http://YOURWEBSITEURL/index.php&quot;);
    }else{
    echo "
    Username/password is incorrect.
    Click here to Login“;
    }
    }else{
    ?>

    Login

    Log In

    Not registered yet? Register Here

  14. Hi Javed

    This is brilliant. For a beginner to understand this it is purely simple and easy to understand code.
    I have used everything as shown, just changed to suit my database and parameters.
    The registration works perfect.

    I had some problems with the login page however.
    First, due to the md5 for password somehow it was reading the key stored in the database. I changed that and that is solved.
    The second issue which i am unable to solve which is actually a repeat by some other comments above, is the redirect after login to the index page where it would show the username based on the session.

    i havent touched your code.

    $query = “SELECT * FROM userdata WHERE username=’$username’ and
    password=’$password'”;
    $result = mysqli_query($con,$query) or die(mysql_error());
    $rows = mysqli_num_rows($result);
    if($rows==1){
    $_SESSION[‘username’] = $username;
    header(“Location: index.php”); // Redirect user to index.php
    }else{
    echo “Username/password is incorrect.
    Click here to Login“;
    }

    The header attribute doesnt redirect to index page to show the Welcome “username”.
    It just reloads the login.php page and remains blank.

    However if i manually navigate to index.php it shows be the details.

    Your views please.

    Thanks
    Hussain

    1. You need to push the login script to the very very top of the page, it can’t be below anything else. It’s a header…

  15. Sir, thanks for the help, but my registration page isn’t connecting to the my database via php myadmin… Pls need urgent reply

  16. hi Javed. this is great tutorial indeed and is simple to understand but one more problem: when do u promise to show us the reset password tutorial? apart from this, I liked your tutorial

  17. Notice: Undefined index: email in C:\xampp\htdocs\DASH\registration.php on line 13
    You are registered successfully.

    Click here to Login

  18. Thanks for perfectly simple example, it’s exactly what I needed. Almost 🙂
    Though, I want to use it only as an addition to another website, yet it insists to make user log in before they can enter main index file.
    Is there a simple way to change this?

    1. I think I figured out – if not logged in, it should redirect to homepage, and not login page.

      if ( !isset( $_SESSION[ “username” ] ) ) {
      header( “Location: index.php” );
      exit();
      }

  19. Hi Javed greetings thanks alot. thanks alot for your tutorial. it really helps… hope i can change the form action to the register.php in my web host?

  20. Thank you for your good work.
    But after registration and login, I only get a blank page.
    If I open index page when I log in, I’ll think so
    BUT, you want to get to index.php directly when you log in.
    This does not help
    Session_start ();
    Require (‘db.php’);

  21. Hi Javed. First of all thanks for the whole tutorial…but after i successful login, it just refresh the login.php but with a totally blank…is it any php tutorial for the connection after login? and after the registration…the data that i key in was not exist in the database…

  22. thank you i have neen using this for some time both versions . recently the <5.5 version has curiously stopped working. i cannot discover if it is a php upgrade or not as my hosting has changed. version now is 5.4.45. shame i love the simplicity of this script

    1. “Warning: session_start() [function.session-start]: Cannot send session cookie – headers already sent by (output started at C:\xampp\htdocs\xampp\seva1\login.php:9) in C:\xampp\htdocs\xampp\seva1\login.php on line 10

      Warning: session_start() [function.session-start]: Cannot send session cache limiter – headers already sent (output started at C:\xampp\htdocs\xampp\seva1\login.php:9) in C:\xampp\htdocs\xampp\seva1\login.php on line 10”

  23. Hi am just using your registration codes, it works well but the datas username,email, password is not showing under my phpmyadmin databse.

  24. I tried to run this on my apache server and when I navigated to the registration page all I got was a blank page. Do you know where I need to save the css file or can I just change the code to include the filepath? Also do I keep or remove all the quotations in the code?

    1. inside the db.php file —-$con = mysqli_connect(“localhost”,”root”,””,”register”); inplace of root you should write your database name and insside “” it is for password and inplace of register you need to place your table name

  25. I’m no expert with PHP, but I do know that md5 is totally unsafe. Shouldn’t be used for anything you care about. Aren’t there better built in PHP functions for encrypting passwords? Also, what about prepared statements SQL queries?

  26. hi, I receive the following errors while trying to register a user.

    Notice: Undefined variable: con in C:\wamp64\Xamp\htdocs\Register\registration.php on line 19

    Warning: mysqli_real_escape_string() expects parameter 1 to be mysqli, null given in C:\wamp64\Xamp\htdocs\Register\registration.php on line 19

    Notice: Undefined variable: con in C:\wamp64\Xamp\htdocs\Register\registration.php on line 21

    Warning: mysqli_real_escape_string() expects parameter 1 to be mysqli, null given in C:\wamp64\Xamp\htdocs\Register\registration.php on line 21

    Notice: Undefined variable: con in C:\wamp64\Xamp\htdocs\Register\registration.php on line 23

    Warning: mysqli_real_escape_string() expects parameter 1 to be mysqli, null given in C:\wamp64\Xamp\htdocs\Register\registration.php on line 23

    Notice: Undefined variable: con in C:\wamp64\Xamp\htdocs\Register\registration.php on line 27

    Warning: mysqli_query() expects parameter 1 to be mysqli, null given in C:\wamp64\Xamp\htdocs\Register\registration.php on line 27

  27. Hi Javed

    This warning message appear when i am opening php file on local host.

    Warning: mysqli_connect(): (HY000/1049): Unknown database ‘register’ in /Applications/XAMPP/xamppfiles/htdocs/db.php on line 8
    Failed to connect to MySQL: Unknown database ‘register’

    What should i do next?

    Thanks
    Sandeep

    1. Dear Sandeep, i would suggest you to create database with name register in your phpmyadmin, this error means it is not able to connect with DB, or you check your username or password.

  28. WOW.
    I just came by this simple registration using PHP/MYSQLI
    It is lovely and a really helpful aid to newbies like me.

    I really wished you could do some advanced user registration tutorial that checks for duplicate users details during registration and validation of fields.

  29. I like your system. Can I add to the registration form a field that accepts a registration number (sent to the user in advance) that validates the number from a database list and then, if valid, continues with the rest of the registration process?
    If so, can the login part of the script then give access to the private folder, or does yet another script have to exist on every html page within the private folder for each page to be accessible?

    1. Well tom, i actually didn’t get you clearly, but if you want to give registration unique no. or id then you can simply fetch the user id and give it to user, and giving access to private folder can be possible but it will be more advance feature, and currently i didn’t write any tutorial about it.

  30. Hi Javed, nice prog. Works OK on my Linux setup. I would suggest in order to increase password security (at least for those who use passwords in Xampp or other database setup and including phpmyadmin, to put the db.php file outside the webroot. In other words put the file in the user root in a directory called ext_include and call that in the login and registration php files as follows ‘require’/ext_include/db.php’; This means that web users cannot readily discover the phpmyadmin (database0 password.
    I have altered it for my own set-up. I will when ready with other small modifications let you know to benefit all.#Well done on this, it saved me a few days headaches and paracetamols. Thanks

    1. Yes you are right, but what i tried here, i simple explain how things work, obviously there is much things for improvement but that should be deal in the later stage, my focus was only to tell the newbie how it actually works 🙂 thanks for your input.

  31. how can I add details to my registration page I mean something like age sex state likes dislikes or for them to choose between security question and all that please how do I go about it

    thanks your tutorial is awesome keep it

  32. when I do the copy paste of what u have instructed it works but I can’t login using the same codes in my other db, but I can register, and when I try to login after registration it shows incorrect username/password even though my username and password are correct….by the way I’ve changed db name in db.php, table name in login.php and registration.php..where should I correct more…plis help!!! presentation nearby 🙂

    1. Sorry for the late reply, i was busy in some other tasks, well i think there may be some issue related to DB connection, you should try to connect db first, if you are changing it, and make sure if you register then its data is in database.

  33. Hi Mr. Javad the code is not complete please I want you to send the code the complete codes of all the attributes in a PDF format into my email please thanks… daniel@**** and may I ask a question…
    Do you know how to design/program a website confirmation like mmm or any ponzi scheme that when any one registers it send activation to some other user?

  34. Goodevening Javed, thanks for the script. I am creating a volunteer website. Assuming I have 10 volunteers who have registered for the program (user-id 1-10), how can I echo the details of user-id 5 (name, phone number and department) to show on the dashboard of user-id 3 and vice-versa. Thanks.

  35. Very good tutorial!
    But I have problem:
    “Warning: session_start(): Cannot send session cookie – headers already sent by (output started at /auth.php:8) in /auth.php on line 9”
    Each file is saved without BOM (UTF-8 BOM). Only UTF-8. What can I do?

  36. I used code in your download but i kept seeing this?

    Warning: session_start() [function.session-start]: Cannot send session cookie – headers already sent by (output started at C:\xampp\htdocs\simple-user-registration-login\auth.php:8) in C:\xampp\htdocs\simple-user-registration-login\auth.php on line 9

    Warning: session_start() [function.session-start]: Cannot send session cache limiter – headers already sent (output started at C:\xampp\htdocs\simple-user-registration-login\auth.php:8) in C:\xampp\htdocs\simple-user-registration-login\auth.php on line 9

    Warning: Cannot modify header information – headers already sent by (output started at C:\xampp\htdocs\simple-user-registration-login\auth.php:8) in C:\xampp\htdocs\simple-user-registration-login\auth.php on line 11

  37. hiiii javed sir i’m very worried about my final year project if you have Online Shopping portel code please send me on my gmail account…
    viju….

  38. I like your code and it seems it will work well. I am having an issue on all pages like registration and login, where when i fill in the information and click on the button, it just reloads the page. No error, no successful message and the database is not updated. I can use INSERT INTO and it will insert into the database so I know it is connected, but it will not do it when i use the register button

  39. Javed; Great Work!

    Any way to add:

    1) That the member registered account expired one year after created?

    2) Registration Code field – a registration code that we will print and provide to the users and when they register need to put on the registration form to validate their account.

    Thanks in advance!

    1. Thanks Samuel,
      Well yes you can create expire date field and enter value in it using date() function, you can enter any date you want, just Google it and you will have lots of date formats along with future dates.
      and for registration code i actually didn’t get you clearly but if you are saying that user will provide registration code which is provide to them manually, then you can simply compare any field using any value either in database or in PHP page if registration code is similar. Otherwise you will need to create another table in DB add all the Reg. Code there and find the user provided code in the table first, if it matches then proceed to register.

  40. Hi Javed,
    When I try to register it gives me this error msg: “Failed to connect to MySQL: Access denied for user ‘root’@’localhost’ (using password: NO)”
    ,so what can I do to fix that??
    Thanks in advance

  41. hi, i cant figure why after i try success register, when i try to login it either give me error message username/password incorrect and blank page, wasnt it suppose to go to index.php? help me.

  42. I have used the code in the download file that you provided. I keep getting this when I login:

    Warning: session_start(): Cannot send session cache limiter – headers already sent (output started at /public_html/login.php:9) in /home/s1541/public_html/login.php on line 11

    Warning: Cannot modify header information – headers already sent by (output started at /home/s1541/public_html/login.php:9) in /home/s1541/public_html/login.php on line 28

  43. Hi Javed,

    Thank you for this simple script and i was able to learn much, but i would like to ask about this part

    require(‘db.php’);
    if (isset($_REQUEST[‘username’])){
    $username = stripslashes($_REQUEST[‘username’]);
    $username = mysqli_real_escape_string($con,$username);

    the username on the if line, whenever i change it the script would stop working/not redirect to any page and i would like to know how does it work or if it does grab something from the db.php, thank you

    1. As you can see that form is submitting on the same page, i am checking here that if this field is filled, which means that form is submitted then perform the actions mention in the parenthesis {}.

  44. Hi Javed,

    This script is simple and straight to the point. Thank you.

    Everything works wonderfully on my site, however, I am having one issue where after login the login.php does not redirect to index.php. So after a successful login, the page refreshes login.php and it is blank. If I manually go to the index.php the session is open and the users info will display correctly. Can you help with the redirect on login to index?

    1. Try to register with plain user and password, like
      username: user
      password: pass

      If your issue is resolved then just simply check mysqli_real_escape_string() function because it escape special characters in variables.

  45. This helped me out! Thanks!
    One small thing I’ve added is an link back from register to login, for users that didn’t want to register but expediently clicked on it.
    Thanks!

  46. Hello javed
    Thank you for sharing this post.
    It worked fine till registration and login but once i registered my self and use the login and password which i have created using registration page it doesn’t redirect to index page but gives this error

    Cannot modify header information – headers already sent by (****/****/public_html/myaccount/register/login.php:11) in /****/****/public_html/myaccount/register/login.php on line 28

      1. I am getting the same message when I try to login.
        ………….. Code is Skipped
        This is the message that i keep getting after logging in:
        Warning: Cannot modify header information – headers already sent by (output started at /home/soiree/public_html/Login/login.php:43) in /home/soiree/public_html/Login/login.php on line 60

  47. Hi Javed, first i would like to tell thanks to you!! The code is going fine upto login page when i enter correct username and password it shows incorrect username or password.

    1. Hi Shamanth thanks that you find it helpful, if you are talking about demo link then i have place there demo user and password, you can login only with that one, or if you have set it up on your local server then you should check after registration that is your registration is going into database? If not then you should enable your local phpmyadmin. Or you can try it online if you have any hosting available.

  48. This is exactly what I needed for my existing website. I’m smart enough to figure how to add more required fields and insert the info to my db. However, is there an easy way for me to display a username on a page? As in “Hi [username], welcome to my site”.

  49. Dear Mr. Javed,

    Thank you for your good work. I need a full payment system script for my small business where my customers can login and make and receive payments. Is this possible

    1. Dear Mark, i am glad that you like it, but for payment system there are various options it depends that which option you want to use, like PayPal, or any other payment method. Script for payment will be vary according to your and payment service provider needs.

  50. Great tutorial! However, it worked fine for me at first but now when I try to register a blank page just appears. Any ideas?

    1. It seems like after clicking on register button you are getting error, although you can see in my code that if form is submitted it must show either error or successful message, if you can explain it in more detail so may i can i figure out what is actually issue you are facing, are you doing it local server or on host? try it host if you are facing issue in local server, may be problem in your local server or not configured properly.

      1. Cheers for the reply. When i attempt to register a user the error or successful message doesn’t load, the page just appears blank. It’s on host just now and I still can’t figure out the error

        1. Try to register with plain user and password, like
          username: user
          password: pass

          If your issue is resolved then just simply check mysqli_real_escape_string() function because it escape special characters in variables.

      1. Hello Javed. Your tutorial and code is awesome. pls can you help implement the query that checks during sign up if a user already exists in the database table; and if it does, the form should display an error message. Thank you so much.

  51. I have tried to make it work but any page that calls the auth.php file seems to just output the code onto the page and not show what it should.

  52. Mr. Javed good day I am Isah from Nigeria I have experienced difficulties in running your code on notepad++ please send the way out through ******

    1. This is Wright Ian, The code works if you always used to mysqli instead of MySQL….. Try it again it works….

  53. Hi there this really help me a lot. How can i implement a function that check user if exist in registration form??

  54. I have got these 2 warnings, please help.

    Warning: mysqli_select_db() expects exactly 2 parameters, 1 given in C:\wamp64\www\fresh\db.php on line 6
    &
    Warning: mysqli_error() expects exactly 1 parameter, 0 given in C:\wamp64\www\fresh\db.php on line 8

    Please help!
    Thank you.

    1. The mysql_select_db() does not work in MySQL Improved, Try adding the database as fourth parameter….

      For example, if I’m connecting to a Db named Wright, I’ll write,

      Mysqli_connect_db(“localhost”,”root”,”password”,”Wright”)
      This works every time for MYSQLI

      1. This is the correct code Mr.Khalfay

        Mysqli_connect_db(“localhost”,”root”,”password”,”Wright”)

  55. Hello!

    I followed the directions here exactly!
    But I can’t seem to get this to connect to my database, I keep getting the code

    “Database Selection FailedAccess denied for user ‘mikereve’@’localhost’ (using password: NO)”

    At the top line of my login page.

    Please advise! 🙂

    1. You need to make sure that you are providing the correct detail for connecting database, commonly root is the user and make sure you are providing the correct password, if there is no password in your phpmyadmin so you do not need to provide password on local environment.

  56. In your registration form, what is the mechanism of user already exists in the database. The same user can be inserted any time. plz check it

    1. Thanks for stopping by, Naveed yes you are right but i didn’t use here to check is user already exist or not, i tried to explain simple registration for newbie users. Yes we can implement so many things in registration form. 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *