130 thoughts on “PHP MySQL Login System with Remember Me, Online Status, Forgot Password & User Profile

  1. i was wondering if you could help me with.
    1.How do i make it so that all the boxes in register must be filled in before they can make an account?
    2.Once a user is logged in or signed in, it redirects them to the index page and the profile button becomes their name?
    3.could you do a tutorial on how to protect your website and how to make a twitter like upload system?
    thank you so much

    1. hmm…

      1. Please see these articles for both client side and serverside form validation:
      http://w3epic.com/how-to-validate-form-with-php-server-side-validation/
      http://w3epic.com/how-to-handling-and-validating-html-forms-in-javascript-tutorial/

      2. Just put $_SESSION[‘username’] or your $username (fetched from database) where you want it to be shown.
      like below

      <h1><?php echo $username;?>'s Profile</h1>
      

      3. Check this out http://w3epic.com/how-to-upload-and-validate-files-using-php/ and tell me if you’re not happy…

      1. Thanks that helped!
        One more thing, how do i let users upload stuff on my website on certain pages? Like yahoo answers, you fill out a form and you choose what category it goes under and they can upload it? how do i do that?
        Thank you

        1. Also i found a ‘bug’? in your simple tutorial if log in was successful it would get rid of the username and password boxes and say you have logged in successfully. How do i redirect people to the homepage if the log n was successful?

        2. Write your upload script on that particular page and along with uploading files, use database to store upload information.
          Then you can play with that with ease.

          1. the code have so many if logged in and ‘else’ i don’t know where to put it so if logged in, you get redirected to the index page. i don’t know what the code is and where to place it.
            thanks

          2. Hey Arpan,
            its not working where i put it

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

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

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

            $user = $result->fetch_array();
            $_SESSION[‘user_id’] = $user[‘id’];
            $_SESSION[‘username’] = $user[‘username’];

            $timestamp = time();
            $sql = “UPDATE users SET status={$timestamp} WHERE id={$_SESSION[‘user_id’]}”;
            $result = $mysqli->query($sql);

            redirect_to(“index.php?id={$_SESSION[‘user_id’]}”);

            }
            }
            if(isset($_GET[‘msg’])) {
            echo “”.$_GET[‘msg’].””;
            }
            if (logged_in() == true) {
            echo “You have Logged in successfully. Click here to go to the main page”;
            } else {
            echo ‘ Oh! No account? Register here!‘;
            }
            ?>

            i don’t know how to let people redirect to the main page.

  2. im testing your script buddy , its good. but i saw some bug. i registered 2 user. after that i log off all. then when i click login without entering any data, it automaticaly logging into user id 2, please advice

    1. Did you clicked on Log Out button properly before that?
      After login with remember me not checked, you close the browser = you log out, without clicking log out link.
      After login with remember me is checked, you do not click on the log out link and close the browser = you stay logged in for 1 week.

        1. I guess you’re running with PHP 5.2, and this is the main reason of this problem.
          Use define in place of const.
          Modify the code of db-const.php like below, instead of the current one.

          <?php
          define('DB_HOST', 'db-host');
          define('DB_USER', 'db-user');
          define('DB_PASS', 'db-password');
          define('DB_NAME', 'db-name');
          ?>
          
  3. Great tutorial,

    I was following your tutorial but I wanted the data from the registration form to be stored into two separate tables, my address_book table includes Address_Book_id, First_Name, Last_Name, Street, Subburb, Post_Code, Phone_Number fields and customers table has Cust_ID, Cust_Username, Cust_Email, Cust_Password, Address_Book_Address_Id fields .

    Could you take a look at my code, and tell me what I have done wrong.

    https://www.dropbox.com/sh/kabgajzg2vfbtvp/AACdVqLBnzcU0wNnqaEffk38a

    Any help would be much appreciated

    1. Hi tedos,
      Can you show me the place near line 128 of your register.php?
      BTW, there is no need of address_book_address_id in customers table. Just add a field ‘customer_id’ in address_book table.
      customer_id will be the link between two tables.

      1. Thanks for the speedy response.

        Line 128 should be there, I have accidentally cut the 1 off so you can only see the 28. So it’s the $sql1 = line.

        127- $sql1 = “INSERT INTO `customers` (`Cust_Id`, `Cust_Username`, `Cust_Password`, `Cust_Email`, `Address_Book_Address_Id`)
        128- VALUES (NULL, ‘{$username}’, ‘{$password}’, ‘{$email}’, ‘{$id}’)”;

        Thanks again

  4. I now get the following *error ( ! ) Warning: mysqli::query() expects parameter 2 to be long, string given in C:\wamp\www\pizza2\register.php on line 130*

    130: if ($mysqli->query($sql,$sql1)) {
    131: redirect_to(“members.php?msg=Registred successfully”);

  5. Hi,
    i think there is a bug? Sometimes it will log in and sometimes it won’t? I have to keep logging in for it to be logged in sometimes? And it dosnt redirect the page like it says in the code?
    Thanks

    1. Hi,
      I rechecked as you said but working as expected – fully functional.
      Something is going wrong with session (in your side).
      1. Clear your browser cache.
      2. Try with different browsers.
      3. If you got any error message, please post it here. (enable php error reporting if disabled)

      1. i see there is a simple tutorial that does the same thing? what is the difference? is this one more secure from hackers or?

        1. Hi Toni,
          In the simple one, I’m just showing 1. creating user’s DB, 2. registering users, 3. logging in
          In the advanced on, I’m adding 1. stay logged in using session, 2. fetch a users info, 3. managing each users online status, 4. remember me option, 5. logout and 6. forgot password option

  6. hello nice detailed script you have created, but am having a similar problem just like how Toni mentioned. Anytime i try to login, I have to try it twice before i can login.

    1. I have the same issue. Here is the error warning message:

      Warning: Cannot modify header information – headers already sent by (output started at /homepages/…/admin/login.php:58) in /homepages/…/admin/functions.php on line 11

      functions.php line 11 -> header(“Location:{$url}”);
      login.php line 58 – if (isset($_POST[‘submit’])) {

  7. I now receive this error “MySQL error no 1452 : Cannot add or update a child row: a foreign key constraint fails (`pepperoni_pizza`.`customers`, CONSTRAINT `fk_Customers_Address_Book` FOREIGN KEY (`Address_Book_Address_Id`) REFERENCES `address_book` (`Address_Id`) ON DELETE NO ACTION ON UPDATE NO ACTION)”

  8. Hi Mike, Toni and anyone having similar problem with login,
    I have checked again and its working fine.
    Have you guys modified anything except db-const.php?
    If yes, please show it to me. Upload your code to dropbox and link it here.
    If you have any online preview of login system, please post the link here.
    Thanks.

    1. Whats in that 48 MB zip file?
      BTW, replace line 106 to 119 with the code below, it’ll fix that.

      $sql = "INSERT  INTO `address_book` (`Address_Id`,`First_Name`, `Last_Name`, `Street`, `Subburb`, `Post_Code`, `Phone_Number`) 
      		VALUES (NULL, '{$first_name}', '{$last_name}', '{$street}', '{$suburb}', '{$post_code}', '{$phone_number}')";
      if (!$mysqli->query($sql)) {
      	echo "MySQL error no {$mysqli->errno} : {$mysqli->error}";
      	exit();
      } else {
      	$id = $mysqli->insert_id;
      	$sql1 = "INSERT  INTO `customers` (`Cust_Id`, `Cust_Username`, `Cust_Password`, `Cust_Email`, `Address_Book_Address_Id`) 
      			VALUES (NULL, '{$username}', '{$password}', '{$email}', '{$id}')";
      			
      	if (!$mysqli->query($sql1)) {
      		echo "MySQL error no {$mysqli->errno} : {$mysqli->error}";
      		exit();
      	} else {
      		redirect_to("members.php?msg=Registred successfully");
      	}
      }
      
  9. Thanks for your reply, I have not modified anything in any of the codes/files except for db-const.php file to connect with Msql and I used your sql.
    An online demo http://fbadder.com/system/login.php
    username mike
    pass mikepass
    Once password is submitted, it remains on the login.. i have to login again or refresh before am redirected to profile.php tested on Firefox and Chrome but the same issue. Thanks

    1. Open up functions.php and change the line no. 11 as below.

      		header("Location:{$url}");
      

      Note that the space after “Location:” is removed.
      After that, check and let me know.

  10. hi Arpan , i have some questions ,,.. i want to remove register page its normal or there anything to notice ?
    i mean i have already database with users and passwords and i dont want any other members to register just my users in my database
    how can it done ???

  11. Great stuff! Found one quirky thing. When a user enters login information and hits “login” all the data from the user name and password fields clear and the form just sits there (even though login was successful). But if you then if you click “login” a second time, it will redirect. Why won’t it redirect the first time and give the success message etc?
    Also, it doesn’t look like it emails users their login info, but perhaps it is not set up to do so? No big deal for me either way…

    1. Hi Jeff,
      It is happening with few people, I’ve tested the code many times, the logic is ok. But somehow redirect is not working for first attempt. Please try with different server and reply.
      I didn’t wanted to put different thing here – it will make it more complex; so I mentioned my PHPMailer tutorial.
      Thanks

  12. your tuts help me a lot..thanks a bunch arpan…could you help me with this…i need to change the email instead username as user login how do i do this? also how do i implement the login page as bootstrap 3 modal ? and for the register form how do i add in the mysql something like member avatar (image) or big photo upload..( i send you the form look arp149[at]yahoo.com…) Any help would be much appreciated

  13. Hi
    Thanks for the great script!
    I got a problem at “register.php”, after I fill up all fields, and press the register Button, it shows up following error:
    “MySQL error no 1364 : Field ‘status’ doesn’t have a default value”

    What I did wrong?

  14. awesome work man, I am gonna try to add a profile picture to the script so when you edit your profile you can upload a .png image, any help you could give me on it?

  15. Hi

    Is this still active as am using this script but have a issue with the log in side/coding

    It keeps coming up with invalid username/password combination

    I have md5 the password so is secure, could that be why?

    Where is best to show the coding, I can use pastebin and add the link here if need be

    1. I’m very busy, but yes – its active 🙂
      If you inserted md5 of the password into database while registering the user, then yes – you have to check through md5 in login page.
      Yes you can post pastebin links here 😉

  16. Hi there gr8 work on this, just one thing that I cant seem to get working, when i click the logout button, it loads a blank page but does not end the seesion, as i can just go back to the profile page and all is still logged in. ?
    thanks in advance

    1. ok i have got this all working now apart from if i add anything els on the login page e.g a p tag with some text in it it stops the login from working ? you have to click the login button again after putting the login details in for it to redirect to the next page?

    1. Hi Sai,
      If we CHECK the remember me checkbox, then we got it in line 33 of login.php
      There, we set the session cookie’s expiration time to one week and we and setting session regenerate id to true in line 34 & 35.
      Thats all 😉

  17. after login I want to redirect home page with view profile,update profile,logout etc option.but there would be no login option (login option was in my home page before login ) because i have already logged in.
    how can i do it?

  18. Hi, I was wondering what if you have 3 users registered, how would you show who is logged on or not, all on the same profile.php so users know who is logged in or not?

  19. Arpan-

    GREAT ARTICLE! Had a quick question:

    I have 4 pages that I would like to require login to view, but they also all share a “”.
    What do I need to add to those 4 pages to require login? And where do its go? In the file itself or in header.php?

    Thanks!

  20. On the login page I have not edited anything and I keep getting the error: “Warning: Cannot modify header information – headers already sent by (output started at …login.php:17) in …functions.php on line 11”
    This seems to be because redirect_to is being called after the page output has started. How do you suggest fixing this? Why didn’t this show up for you when you originally created this code?

  21. Fatal error: Call to a member function fetch_array() on a non-object in /home/coldcodrr/public_html/logout.php on line 16

    Logout isn’t working, please help!

    1. // update status to offline
      $sql = “SELECT status from users WHERE id={$_SESSION[‘user_id’]}”;
      $result = $mysqli->query($sql);
      $user = $result->fetch_array();
      $timestamp = $user[‘status’] – 300;
      $sql = “UPDATE users SET status={$timestamp} WHERE id={$_SESSION[‘user_id’]}”;
      $result = $mysqli->query($sql);

  22. Hey! this the best tutorial for this lessons ever! please share it with your friends.

    i would like to know how to receive other information for other online users through profile? anyone can help me please!!!!!

  23. I have faced some problem.

    Notice: Use of undefined constant localhost – assumed ‘localhost’ in C:\xampp\htdocs\Project1\profile.php on line 26

    Notice: Use of undefined constant root – assumed ‘root’ in C:\xampp\htdocs\Project1\profile.php on line 26

    Notice: Use of undefined constant database – assumed ‘database’ in C:\xampp\htdocs\Project1\profile.php on line 26

    The error code is in the profile.php
    ## connect mysql server
    $mysqli = new mysqli(localhost, root, “”, database);

    Actually the real code is
    $mysqli = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME); but i have changed it like above n i couldnt find the solution for it.
    Could u help me with this and thanks in advance.

  24. If you are getting function fetch_array() on a non-object on logout.php

    Change to the following

    // update status to offline
    $sql = “SELECT status from users WHERE id={$_SESSION[‘user_id’]}”;
    $result = $mysqli->query($sql);
    $user = $result->fetch_array();
    $timestamp = $user[‘status’] – 300;
    $sql = “UPDATE users SET status={$timestamp} WHERE id={$_SESSION[‘user_id’]}”;
    $result = $mysqli->query($sql);

  25. Keep getting this error after the code tries to redirect to any page, be it register, login, go to profile or logout

    Warning: Cannot modify header information – headers already sent by (output started at /customers/c/8/0/feedits.com/httpd.www/test login/profile.php:15) in /customers/c/8/0/feedits.com/httpd.www/test login/functions.php on line 11

    what do i need to do to correct the redirect_to function

  26. Thanks, System is working great, however I am just about to update my site to use Bootstrap, do you have any advice on modifying this script to work with Bootstrap (using Dreamweaver CC 2015), login using modal popups etc

  27. Hi,

    thank you so much for the tutorial!

    It should be working fine, but whats that?

    Warning: mysqli::mysqli(): php_network_getaddresses: getaddrinfo failed: nodename nor servname provided, or not known in /Applications/XAMPP/xamppfiles/htdocs/viduals.com/register.php on line 98

    I basically can´t register.

    Hope you see this, thank´s much,
    Oliver

  28. Hello..No doubt this is awesome….
    I’m getting this error.

    Warning: mysqli::__construct(): php_network_getaddresses: getaddrinfo failed: No such host is known. in C:\xampp\htdocs\register.php on line 31

    Warning: mysqli::__construct(): (HY000/2002): php_network_getaddresses: getaddrinfo failed: No such host is known. in C:\xampp\htdocs\register.php on line 31
    MySQL error no 2002 : php_network_getaddresses: getaddrinfo failed: No such host is known.

    any guidance..

  29. I’ve replaced all mysqli to mysql…..
    now getting this error

    Fatal error: Uncaught Error: Class ‘mysql’ not found in C:\xampp\htdocs\register.php:31 Stack trace: #0 {main} thrown in C:\xampp\htdocs\register.php on line 31

  30. Hi there, i was suffring with a error in register page:-
    Trying to get property of non-object in C:\xampp\htdocs\myweb\register.php on line 53

    and login page:-
    Trying to get property of non-object in C:\xampp\htdocs\myweb\login.php on line 48

  31. thank you for this great lesson….please if I want non login users to also view others profile…..and let a loved in user to view other profile apart form his own how will I do it…. thaks

  32. every thing is ok but when i click on forget password then program demand email id from me and i entered my email id but when i open my email id then there is no any information regarding my password

    plz solve this problem

  33. Your downloadlink (dropbox) results in Errormessage
    Error (429)
    This account’s links are generating too much traffic and have been temporarily disabled!

    That is the result of beeing so popular 😉
    Any alternative download links ?

          1. yes, i know where the error is. its in the connection. not the db-const.php but in the login.php. there you will connect to the database and thats going wrong. this works as well: (i hope you can read it, because its code) it is the 4th line: $conn = mysqli_connect. how to fix it?

            i hope this is the right problem. other i ask you or search on the web. have a nice day!

  34. After registering as new user I receive this message :

    MySQL error no 1364 : Field ‘status’ doesn’t have a default value
    What when wrong?

    Thanks in advance.

  35. Sir, please help me urgent, sir iam using your script since 6 moths but now i saw some serious issue on login page as it is not protected from SQL Injection, sir please make some changes in login.php page and make it protected from sql injection..

    Please replay waiting for your replay….please…

  36. Dear Arpan,
    You posted very nice and helpful tutorial. I need a help from you and that is I need a php script for “membership expiration system (for a certain time user will browse the web site)”. Would you kindly share this type of tutorial with full code please?

  37. Hie

    I saw your login tutorial.I however have one request from you.Is it possible that you add for me table or field in the database that will hold amounts.I need to use that one as an account system where users login to check their balance that i will be updating from the back-end daily

  38. hi sir good evening, i want to create a matrimony website but i am new to php could you please send some scripts to me please. (so far i have created the registration system with some updated options only)

Leave a Reply

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