140 thoughts on “PHP MySQL Login System – A Super Simple Tutorial

    1. it says #1044 – Access denied for user ‘id1594579_login’@’%’ to database ‘information_schema’

  1. if (!$result->num_rows == 1) {
    echo “Invalid username/password combination”;
    } else {
    echo header (“Location:page1.php”);

    i Want to use this Kindly tell me . This Gives error Cannot modify header information – headers already sent by

    1. Hi Gurmeet,
      Header must be sent before any output is made.
      Do not output anything before the header call. Move your code to the very beginning of the file, before any output.
      Also check for accidental white spaces before “<?php”, like below:
       <?php //code… ?>

  2. Access forbidden!

    You don’t have permission to access the requested object. It is either read-protected or not readable by the server.

    If you think this is a server error, please contact the webmaster.

    Error 403

    2/6/2014 9:54:19 PM
    Apache/2.2.14 (Win32) DAV/2 mod_ssl/2.2.14 OpenSSL/0.9.8l mod_autoindex_color PHP/5.3.1 mod_apreq2-20090110/2.7.1 mod_perl/2.0.4 Perl/v5.10.1


    What will I do with this error. Please help. Thanks! 🙂

      1. Hello, I already fixed that error. Now have another error. Everytime I try to register or login, it always shows “Invalid username/password combination” even though I put the right input. What should I do? Thanks! 🙂

  3. How do I make certain pages only visible to logged in users. Also is there a way so that upon registration admin has to approve the user?

    1. Hi,
      To do that, store the login status for each user to their browser using session and then on that page use the code below.

      < ?php
      if (logged_in() === true) {
      //show the page content.
      } else {
      // not logged in - redirect to login.php
      header("Location: login.php");

      logged_in function must be defined.
      For the approve part, add a field “approved” to your users table on database. Then on registration page, set default “approved” value to false. Now you’ve to approve the user (update “approved” value to true).

      1. Could I write this in login.php ;
        $username = $_POST[‘username’];
        $password = $_POST[‘password’];
        $approve = $_POST[‘approve’];

        $sql = “SELECT * from users WHERE username LIKE ‘{$username}’ AND password LIKE ‘{$password}’ AND approve LIKE ‘[$approve}’ “;

        And then something along the lines of

        1. Hi, you can try like this –

          On the register.php,

          $sql = "INSERT  INTO `users` (`id`, `username`, `password`, `first_name`, `last_name`, `email`, `approved`)
          VALUES (NULL, '{$username}', '{$password}', '{$first_name}', '{$last_name}', '{$email}', 'false')";

          On the login.php

          $sql = "SELECT * from users WHERE username LIKE '{$username}' AND password LIKE '{$password}' AND approved LIKE 'true' LIMIT 1";

          On the login.php, there is no need to pass $approve variable in the sql. Because we’ll only let a user login if he/she is approved. So, it’ll be always true while querying the database.

          1. thank you I see what I was doing wrong, for the sessions , is this suitable as the logged_in() function;
            function logged_in() {
            return (isset($_SESSION[‘login’])) ? true : false;
            Can you add an email upon registration in the registration.php or does there need to be another?

        1. Hi Rene,
          This article is just about a simple login system, no session is used. So we’ll be able to just login – but it will not be kept.
          To keep a user logged in, at the very beginning of login.php put session_start(); before any character is printed.
          Then user $_SESSION[‘userID’], $_SESSION[‘expiry’], etc. to store user data and keep a user logged in.
          As I said to Conner, I’ll post a tutorial about remember me and log out facility ASAP. It’ll be extension of this post.
          Thank you.

        1. The code is okay. Are you getting this error on both register.php and login.php?
          I’m sure there must be some misconfiguration in apache. Try to install Apache 2.4.2.
          To install, download Apache 2.4.2 and extract to \wamp\bin\apache
          Then start WAMP server > select Apache > Version > 2.4.2

    1. Hello lillycrak,
      I’m really sorry for the delay, I’ve not noticed your comment.
      You can do an AJAX call on each link of your page and send the required data to something like process.php
      Then fetch the data, process it and store it into database from process.php
      Thank you

  4. Hello! I get this error when registering an account “MySQL error no 2005 : Unknown MySQL server host ‘SERVER’ (0)”. Whats the problem and how do I sort of link this to a members area only. Please don’t criticise me, I’m new to php

    1. Hello Carl,
      Please be confident, no one will criticize you! You do mistakes === You learn something!
      The error is caused by putting wrong MySQL Server Host info. Please change MySQL host with correct value. It may be located at config.php or db-config.php or whatever you named and stored it 🙂

  5. After Registration when i clicked the submit button It showning like this.. And i using xampp
    How to fix it?????
    Warning: mysqli::mysqli(): php_network_getaddresses: getaddrinfo failed: No such host is known. in C:\xampp\htdocs\login\login.php on line 20

    Warning: mysqli::mysqli(): (HY000/2002): php_network_getaddresses: getaddrinfo failed: No such host is known. in C:\xampp\htdocs\login\login.php on line 20

    MySQL error no 2002 : php_network_getaddresses: getaddrinfo failed: No such host is known.

    1. Hi Suriyakmr,
      Right parameter order of mysqli_connect() is:

      mysqli_connect("host", "user-name", "password", "db-name")

      I guess you’ve swapped values like this

      mysqli_connect("user-name", "password", "host", "db-name");
  6. Hi There,

    How can i make a log out facility ? im thinking of an end_session() function but what would be defined !, any help is appreciated 🙂 and a great tutorial !


  7. Hello,
    I have already seen comments questioning this but I was able to get all of this code to work great with my page, I just want to make it so that once the user is logged in, they will be recognized as being logged in and will have access to pages that require the user to be logged in. You say to put session_start() in, do I need to put that in every php code area? Also, after all of the php code in login.php, am I supposed to add more information so that the session is officially started and the user is recognized? Finally, what do I need to place at the top of every page that I need to be secure and have the user be logged in for?

    1. If you are willing to give me your email address, could I send you my code and you can look at it and help me? I’d really appreciate it.

  8. Thank you very much man, i’ve been stuck on this shit 2 days and this made ir for me, again thank you so much

    1. Hi Syafiq,
      While registering a session on client side, you need to send them to server via GET/POST.
      After that, you can display them or do whatever you want with the data you got.

  9. Hey, how do i allow logged in users to stay logged in within all the different pages? what is the php code i need to add at the top of each page to do this? and how do i change a logged in button to ‘your account’ when logged in? thank you so much, if i make money from my website i will be sure to donate some to you (y).

    1. Hello DP,
      For the first problem, you need to put session_start() in the very first of the login page.
      For the second problem, at first you have to create a field called ‘online_status’ (or whatever you want) in your users DB.
      Then just follow the pseudo code below to solve your problem.

      when a user logging in, set the value of 'online_status' of that particular user to == 'online';
      and when a user logging out, set the value of 'online_status' of that particular user to == 'offline';
      now, on the profile page of a user - fetch the value of that user's DB field 'online_status' and show it on profile page;

      Hope you got it, thanks for being so nice. Good luck for your website.
      BTW, I going to write a separate tutorial on the same topic in details very soon 🙂

      1. That was very confusing for me haha, could u please show me the code to put on the start and i don’t understand what you mean by ‘online_status’

        1. Hmm… where you are storing your users’ data? using a MySQL Database is most efficient way to store such kind of data.
          Each databases has one or more tables. Each table has one or more data fields. See the table below and assume its you users table. Here online status is s data field (column).

          user_ID       |user_name     |password      |online_status
           1            | dp           | apwd         | online
           2            | arp          | anotherpwd   | offline
          1. I’m still having quite some trouble, could you please give me your email address so i may contact you if its no trouble? Thank you

  10. redirecting with header() is not working at ‘do stuff’ section. also i’m trying to change an element’s content but nothing…

  11. My code again:

    <form method="post" action="">
    	<4 href="./admin/passwordRecovery.php" rel="nofollow">He olvidado mi contraseña...</a>
    if (isset($_POST['submit'])){
    	$email = $_POST['email'];
    	$password = $_POST['password'];
    	$regex = "/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i"; 
    	// Run the preg_match() function on regex against the email address
    	if (!preg_match($regex, $email)) {
    		echo 'document.getElementById(\'error_message\').innerHTML = "fsdf"';
    	} else {
    		if (login($email, $password, $mysqli) == true) {
    			// Login success
    			header("Location: graficas.php");
    		} else {
    			// Login failed
    			$dom->getElementById('error_message')->nodeValue = 'El email debe tener un formato válido!';
  12. Hi, is this still active and am using this script I am doing for a new client and he wants to approve users first so found the part mentioning about approval and added a extra column to the users table called approved and added in the register and login php files the coding mentioned but what would the coding be to build a php page for the admin side to approve the user

    Thank you in advance

    Kind regards


    1. Hello,
      Sorry, I did not noticed that you are using my script for your client.
      This script is very very basic of a PHP MySQL login system.
      There is no data sensitization is done here, so the script is vulnerable!
      Do not use this script on production environment.
      I’ll not be responsible for any damage to your client.

  13. Hi

    I really like this script but how can I make it so that admin approve users rather than having automatic registration by email activation link etc

    Kind regards


    1. make a column in your users table and lets name it “active”. Set it false while registering a new user. You can limit user’s activities based on this “active” flag. Later create a admin page to approve the user by updating the value to true.

  14. One of the worst login systems. Vulnerable to a everything. Do NOT follow this stupid tutorial. Author has no idea about coding a secure PHP login system.

    1. Hi,
      Are you kidding? Yes it is vulnerable because I’ve created this in that way.
      I think you have not even read this article where I’ve clarified that – “we will not sensitize and validate user provided data to keep it as simple as possible.”
      So, I build it as simple as possible, for beginners – not advanced users.
      There is no security provided in this login system, its just to clarify the login concept.
      Thanks for the ping, I’ll post another article about securing a PHP MYSQL login system. I’ll notify you – then you can complain.
      Thanks for commenting 🙂

      1. When you write a tutorial, you try to teach the beginners good habits and the “right way” of doing something. This is the purpose of a tutorial. How difficult is to use prepared statements, so the beginners learn from the beginning the good habits? It just takes 1-2 extra lines for each query and it takes you 3 more seconds to write this code. For example: 1 comment above (“Ian Haney”) said he is coding a login system for a client using YOUR tutorial. You did not tell him not to follow this tutorial since this code its vulnerable and will only cause problems in the features.

        For me either you write a tutorial about how something should be done or you just simply do not write it. I am coming from a forum and a user found this tutorial on google and it just gave me cancer! I had to teach him all the basics that needs to know, instead of this!

        1. Yeah, I should have been added a disclaimer first. I apologize that I did not even noticed that he is using this for his client – thats my fault. But how could I guess that a beginner who is just learning a PHP login system have a client.
          But, I’m not agree to use prepare statement here. Many will confuse about prepared statements and loose their interest.
          “How difficult is to use prepared statements?” It may be easy for you, for me but not for one that who is learning a PHP login system from scratch.
          A kid cannot learn coding without learning alphabets, habit comes later. I think that 1-2 extra lines will make it much more complex to them.
          I’m taking the good part of your advice.

        2. Your title says a lot about you. Arpan is an excellent teacher in his materials and has done an excellent job of helping people here. Most of us already know that what we do with the code demonstrated is our problem. You being so uppity and righteous, should direct us to your superior teaching sites. I’m betting there is no such existence. There will always be a self-righteous critic.

  15. HI ARPAN

    I keep getting a syntax error in this line defined as an unexpected T_string

    if ($mysqli->connect_error no)
    How do i go about it?

  16. DB file contains username, password and flag.
    for select it from DB i give (“select * from file name”);
    is it correct? or Any other way? PLz help me…

    1. Hi,
      No, thats not file name. Open up phpmyadmin and import the file using import tab.
      Then it should be “SELECT * FROM users;”
      Note: users is the table name in your database.

  17. Hi Arpan Das,
    I am a beginner at this php material. I believe your teaching (presenting the basic concepts first) is very great.
    I would like to copy and validate user ID and EmailAddress from users in session on http://www.mysite/startpage to a database (i need to create) at http://www.mysite/added_information after they click and fill the “Added Information Form” found on “startpage”

    I need to do this manipulation to verify that the date they enter in the Added Information Form has the same User Id and Email that they logon with to access “first page”.

    Will the training you give so far be sufficient to accomplish that?

    Next question: ?how do I locate/identify the user table/data location from http://www.mysite/startpage (which is an open source program I bought), so that I can program the

    $sql = “SELECT * from users WHERE username LIKE ‘{$username}’ AND email LIKE ‘{$email}’ LIMIT 1”;
    $result = $mysqli->query($sql);
    if (!$result->num_rows == 1)

    1. Hi,
      Sorry for the late reply,
      You are thinking with very complexity. Be cool 🙂
      You can do this manipulation in the same page.
      register.php : To add new users data to the data base.
      login.php : It takes a unknown user’s data and checks for if the unknown user does exist in the database with right username:password combination or not. If user found, then the unknown user is got known and we let him access some restricted pages (like a atm card and atm machine).
      , see the login.php above.
      There is no need of added_information.
      Now, if the login form is submitted, we get the unknown users data and the sql part goes here.
      Yes this is enough to accomplish that.
      I suggest you to see this also: http://w3epic.com/php-mysql-login-system-remember-online-status-forgot-password-user-profile/
      Thank you very much 🙂

  18. Warning: mysql_connect(): php_network_getaddresses: getaddrinfo failed: No such host is known. in C:\xampp\htdocs\test\members_area\config.php on line 12
    Members Area ……. problem ta kano ho6he?????????

  19. User registration form- PHP MySQL Ligin System | W3Epic.com

    Parse error: syntax error, unexpected T_CONST in C:\wamp\www\New folder (7)\db_const.php on line 3

    why error to my :((

    1. Hi Steve,
      Try this out –

      	if (isset ($_GET['submit'])) {
      		## connect mysql server
      		$mysqli = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
      		# check connection
      		if ($mysqli->connect_errno) {
      		echo "<p>MySQL error no {$mysqli->connect_errno} : {$mysqli->connect_error}</p>";
      		$query	= $_GET['query'];
      		$result = $mysqli->query("SELECT * FROM users WHERE username like '%{$query}%'");
      		// fetch result
      		while ($row = $result->fetch_array()) {
      <form method="get">
      	<input type="textbox" name="query" />
      	<input type="submit" name="submit" value="Search"/>
      1. hi
        I have 100 college login .. i need to redirect to all based on their id which is registered … that will be done by single login page …

  20. Is line 9 in the register.php supposed to read:

    echo “MySQL error no {$mysqli->connect_errno} : {$mysqli->connect_error}”;


    echo “MySQL error no {$mysqli->connect_error} : {$mysqli->connect_error}”;


    is “errno” calling an item or is it a typo for “error”?

  21. Hello Arpan,
    Thank you it’s very useful for my next project. Why don’t you user code highlighter. As it is quite difficult to read the code and understand. If you use wordpress then there is a plugin search for “Syntax highlighter” and it will come

  22. hi man!

    i copied all your codes . here is the message that i got
    “Invalid username/password combination”
    do i need to create a my pass and user in mysql or any user and pass can work?
    thanks for your help

  23. Would there be a way for a page to remember a user’s name when logged in, I kinda want to make a webpage where you would be able to post comments and other things with your account and I need the website ro remember the full name of that person and display when posting some stuff…

    (Sorta facebook, but personal and have less informations, just posts and comments)

    If you have any other things that could help me, that would be really helpful (you don’t have to tho…)

  24. thank you so much for this tutorial. It really help me for my assignment.. thank you.thank you..

    god bless you!


  25. please help,error in line 32 and below is the line i have copied your code

    Trying to get property of non-object in C:\xampp\htdocs\login\login1.php on line 32

    if (!$result->num_rows == 1)

  26. in db_const.php giving error to the # mysql db constants DB_HOST, DB_USER, DB_PASS, DB_NAME
    const DB_HOST = ‘SERVER’;
    const DB_USER = ‘USER’;
    const DB_PASS = ‘PASSWORD’;
    const DB_NAME = ‘php_mysql_login_system’;
    to this lines.
    plz give mi rpl as early as possible

  27. After a looooooooooooooong time of searching, i finally find the answer… Thanks man for the absolute amazing tutorial

Leave a Reply

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