Develop User Signup and Login forms: PHP & MySQL


PHP & MySQL tutorial to develop signup form and store user information in a database and using signin or login form we compare for the correct username and password combination in our database. We also use session and demonstrate session_start(), session_unset(), session_destroy().

php-login-session

This tutorial is very important for any of your projects where you want to implement authentication: user signup and signin. So this is a crucial part of your online application. So better spend some time to understand the working. Watch the video and try to code on your own. And please make sure to contribute back to the community by commenting and sharing what you have learnt, in the comment section below.

Video Tutorial: Develop User Signup and Login forms: PHP & MySQL


[youtube https://www.youtube.com/watch?v=mn0ucCuNOTI]

YouTube Link: https://www.youtube.com/watch?v=mn0ucCuNOTI [Watch the Video In Full Screen.]


In this tutorial we are using MySql database, PHP, and some HTML coding to design the forms.

Complete Source Code and Explanation:

For Database connectivity:(db.php)

<?php
     $conn = mysql_connect("localhost","root","");
     $db   = mysql_select_db("technotip",$conn);
?>

Instead of writing the database information again and again, we have moved this to one file(db.php) and call/include that file in all the scripts which needs to connect with the database.
Here localhost is the hostname. In 95% of the time the hostname will be localhost. If you are using a grid based hosting service, then it will be your grid number followed by .gridserver.com ex: xxxx.gridserver.com

We are using localhost, root is its username. We do not have any password, so we have left the next field blank.

Next line of code is to select the database present in our localhost. Here we have created a database called technotip. Below is the MySQL syntax to create the database.
Creating Database:

mysql> create database technotip;
mysql> use technotip;

First line of code is to create the database, and the next line is to start making use of the created database.

Table Creation:

mysql> CREATE table phplogin( id int, username varchar(15), password varchar(20));

To keep things simple, we are creating only 3 fields in the table: id, username, password.

To Check the table description/structure:

mysql> desc phplogin;

To see the table entries:

mysql> SELECT * from phplogin;

A Form for People To SignUp(signupform.php)

 
 <html>
        <form action="signup.php" method="post">
              Username:<input type="text" name="n"><br />
              Password:<input type="password" name="p"><br />
              id      :<input type="text" name="id"><br />
              <input type="submit">
        </form>
 </html>

In signupform.php we are using post method, because we will be using password and it should not be shown in the address bar of the user!
Let the name for each input field be unique, as we will be using this to receive the user input data in another file which is pointed by form action.

GET v/s POST method
The GET method produces a long string that appears in your server logs and in the browser’s address bar.
The GET method is restricted to send upto 1024 characters only.
Never use GET method if you have password or other sensitive information to be sent to the server.
GET can’t be used to send binary data, like images or word documents, to the server.
The data sent by GET method can be accessed using QUERY_STRING environment variable.

The POST method does not have any restriction on data size to be sent.
The POST method can be used to send ASCII as well as binary data.
The data sent by POST method goes through HTTP header so security depends on HTTP protocol. By using Secure HTTP you can make sure that your information is secure.

signup.php file

<?php include_once("db.php"); ?>
 
<?php
           $user = $_POST['n'];
           $pass = $_POST['p'];
           $id = $_POST['id'];
        #$sql = "INSERT into phplogin values(".$id.",'".$user."','".$pass."')";
          $sql = "INSERT into phplogin values($id,'$user','$pass')";
           $qury = mysql_query($sql);
 
        #  INSERT into phplogin values(
        #   1,
        #   'satish',
        #   'satish');
 
        if(!$qury)
        {
                  echo "Failed ".mysql_error();
                  echo "<br /><a href='signupform.php'>SignUp</a>";
                  echo "<br /><a href='signinform.php'>SignIn</a>";
        }
        else
        {
                  echo "Successful";
                  echo "<br /><a href='signupform.php'>SignUp</a>";
                  echo "<br /><a href='signinform.php'>SignIn</a>";
        }
?>

Using include_once(), we are including the file db.php By including this file, we automatically get connected to the database.
We use $_POST because we have used post method in signupform.php form.
We can use either of the two MySQL query to insert the values into our table phplogin.

       $sql = "INSERT into phplogin values(".$id.",'".$user."','".$pass."')";
                                   OR
       $sql = "INSERT into phplogin values($id,'$user','$pass')";

Integer values need not be enclosed within single quotes, but the string variables(and values) must be enclosed within single quotation mark.

mysql_query() is used to execute the query. You can directly pass the query as parameter to this standard PHP function.
Based on the result of execution of above query we display a “Success” or “Failure” message and display some HTML links for further navigation.

Login Form: (signinform.php)

 
<html>
       <form action="signin.php" method="post">
              username: <input type="text" name="name"><br />
              password: <input type="password" name="pwd"><br />
              <input type="submit">
       </form>
</html>

This is same as signupform.php form, with minor modification to the input field. And the form action is pointing to signin.php file. Here also we are using post method.

signin.php

<?php 
 
  include_once("db.php"); 
  session_start();
 
?>
 
<?php
 
     $uname = $_POST['name'];
     $pass = $_POST['pwd'];
 
     $sql = "SELECT count(*) FROM phplogin WHERE(
     username='".$uname."' and  password='".$pass."')";
 
 
#     SELECT count(*) FROM phplogin WHERE(
#     username='$uname' and  password='$pass');
 
      $qury = mysql_query($sql);
 
      $result = mysql_fetch_array($qury);
 
      if($result[0]>0)
      {
        echo "Successful Login!";
        $_SESSION['userName'] = $uname;
        echo "<br />Welcome ".$_SESSION['userName']."!";
        echo "<br /><a href='signupform.php'>SignUp</a>";
        echo "<br /><a href='signinform.php'>SignIn</a>";
        echo "<br /><a href='logout.php'>LogOut</a>";
      }
      else
      {
        echo "Login Failed";
        echo "<br /><a href='signupform.php'>SignUp</a>";
        echo "<br /><a href='signinform.php'>SignIn</a>";
      }
?>

First we include the db.php inorder to connect to the database, so that we can compare the user entered credentials with the actual username and password present in our database.
Here we are also starting the session. session_start() is the start call for the session and is a mandatory step, if you want to use session in any of your PHP script.

   $sql = "SELECT count(*) FROM phplogin WHERE(
     username='".$uname."' and  password='".$pass."')";

Using above MySQL query, we pass the user submitted username and password to our table and check if there is any presence of such combination of username and password. If the result is 1, then the username and password combination is present. If it returns 0, then there are no such a combination of username and password in the database: that means, login failed.

So, according to the result obtained we display the message and further give some links for navigation purpose.

If the login is successful, then we create a session variable with name userName and then assign the username to it.

        $_SESSION['userName'] = $uname;
        echo "Welcome ".$_SESSION['userName']."!";

and we display Welcome userName! message, which looks like a customized welcome for each person who logs in successfully.
Once the user is logged in successfully, we provide a link to log out. Which is explained after the below snippet of code.

Logout (logout.php)

<?php
 
session_start(); # Starts the session
 
session_unset(); #removes all the variables in the session
 
session_destroy(); #destroys the session
 
if(!$_SESSION['userName'])
   echo "Successfully logged out!<br />";
else
    echo "Error Occured!!<br />";
 
?>

Above code is to illustrate a simple way of working of session.

session_start(); # To Start the session

session_unset(); # Unsets/Removes all the variables in the session

session_destroy(); # Destroys the session

To demonstrate whether the logout process has removed/destroyed the set session variable, we have used the if statement, where in we check if the session variable is set or not. If still set, then the logout process isn’t working. If the session variable is destroyed/unset, then the logout successful message is displayed.

   if(!$_SESSION['userName'])
        echo "Successfully logged out!
";
    else
         echo "Error Occurred!!
";

In above tutorial we have taken much time to link to signup and signin forms, this may look trivial; but in practice these are very important for better user experience and usability factor. So make sure you provide options for your users so that they can do something when they are landed on a page. If the page is empty and there are no links to navigate, then the user may get puzzled! Instead, if you have links to the profile and a log out link, then the user can choose, where to go next.

Please share the above video tutorial with your friends on Facebook, Twitter etc, and subscribe to our blog and YouTube channel. All the best for your application development. We are excited and eager to hear about your application development in the comment section.

76 thoughts on “Develop User Signup and Login forms: PHP & MySQL”

  1. Im very thankful to you,i was trying to sort out this from so many days,i didnt find such a good tutorial hats off to you guy……and a little bit of error…just sort it out

    im getting the error when im logging out……here is the error

    ( ! ) Notice: Undefined index: Email in C:\wamp\www\phploginsession\logout.php on line 11
    Call Stack
    #TimeMemoryFunctionLocation
    10.0004140096{main}( )..\logout.php:0
    successfully logged out

    and the code is

    <?php

    session_start();

    session_unset();

    session_destroy();

    if(!$_SESSION['Email'])

    echo "successfully logged out";

    else

    echo "Error Occured!!”;

    ?>

    and also i want another help from you….when the user logs in,instead of
    the text “succesfully logged in” i want to open an php page when he clicks the submit button…so how to do it….please help me out

  2. @satish : hello, thanx dude i have just overcome with the problem i have posted in my last comment…..Great tutorial thanx a ton.

    A little more help from you….can you bring us with a tutorial for validating forms fields with php at server side….forms fields such as
    1.Username (should allow letter as well as numbers and max length of 6)
    2.Password (should not allow spaces and max length of 6)
    3.Email (should be a valid email)
    4.Mobile no (should start with either 9,8,7 and max length of 10 digits)

    i will be really thankfull to you…help me

  3. 0)
    {
    print”Sucessfull login”;
    }else
    {
    print”login failed”;
    }

    ?>

    I am using wampp server and getting this error message

    ( ! ) SCREAM: Error suppression ignored for
    ( ! ) Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in D:\wamp\www\databases\singupsigninform\login.php on line 13
    Call Stack
    #TimeMemoryFunctionLocation
    10.0005142392{main}( )..\login.php:0
    20.0141149576mysql_fetch_array ( )..\login.php:13
    login failed

    plzzzz help me. i am geeting annoyed of changing the code so times

  4. @mani, Mani, sorry the coding isn’t displayed here so I’m unable to help you at this time. Could you please get on to our forum and ask your question? I would be glad to try my best to help you out of this problem.

    As far as I understand by the error message: you are passing wrong parameter to mysql_fetch_array ( )
    make sure the MySQL query is valid, so that the $res = mysql_query($query);
    will yield proper result, inturn pass it to mysql_fetch_array( $res );
    which should work properly.

    Hope it helped, if not: please post the code and error message on our forum. Thanks

  5. This is my signin.php script.

    if($result[0]>0)
    {
    echo “Successful Login!”;
    $_SESSION[‘userName’] = $uname;
    header(“Location:/realdirectory/index.htm”); // redirects
    echo “Welcome “.$_SESSION[‘userName’].”!”;

    There is some kind of security hole here. User is able to bypass the login by entering doman.com/realdirectory/index.htm straight away. How to prevent this ?
    }
    else
    {
    header(“Location:/ade.htm”); // redirects
    }
    ?>

  6. @leezhijiang, in /realdirectory/index.htm check if the session has been set. if not, redirect the user to login page again. That’s it.

    Sample code:

    index.php

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    
    < ?php
         session_start();
     
         if(!(isset($_SESSION['userName'])))
         {
              // header('Location: login.php');
              echo "You're not logged in";
              exit();
         }
         else
         {
              echo "Successfully logged in!";
         }
    ?>


  7. i have a question, how to make a hyperlink in php that when user clik then it will point to the current session?for example, when user hover the link, it will show update?id=”user session”

  8. @lan, nice question. We usually get such situations in real time application developments.

    This is simple though:

    assign the value inside the session variable to a local variable and then use its value to link.

    1
    2
    3
    4
    5
    6
    7
    
    < ?php
     session_start();
     
     $username = $_SESSION['userName'];
     
     echo '<a href="update.php?id=$username" rel="nofollow">Edit< /a >';
    ?>

    This would easily solve your problem.
    Hope this helps :-)


  9. I really appreciate your help Satish :). I still have a problem, because I combine php and html at once.
    I have declared $ username = $ _SESSION [‘userName’]; during session start, then I called it in

    1
    2
    3
    
    <a href="kemaskiniprofil.php?id=$username" rel="nofollow">
    update profile 
    </a>,

    then what happens is it just show kemaskiniprofil.php? id = $ username .. can you explain more? I really appreciate your deeds

  10. @lan, I guess, its mistake of single and double quotes combination.

    Single quotes: it displays string as it is. including $username
    Double quotes: displays string and replaces variable names with its values.

    So try this:

    1
    2
    3
    4
    5
    6
    
    < ?php
     session_start();
     
     $username = $_SESSION['userName'];
     echo "<a href='update.php?id=$username' rel="nofollow">Edit< /a >";
    ?>

    observe the changes in quotes in echo statement.

    Remove rel=”nofollow” attribute, as its getting automatically added by our comment system.


  11. can u modify my coding?

    this is initializing the session on this page

    and this is the line of html where the session need to to be point to

    kemaskini profil

    *no_mykad_pelanggan is primary key.

    this is the flow of the system, first user need to login in 1st page, then if login success, the user page will appear. in this page, the user can update his profile detail which is the link above. this link suppos to be “kemaskiniprofil.php?no_mykad_pelanggan=”IT PRIMARY KEY”..

  12. I found this very interesting; i tried it but every time I press the submit button the entire php code in the signin.php page keep displaying. I go over your solution over and over but cant see why that is happening. Can you please tell me what could cause this. Thanks in advance.

  13. @lan, @leezhijiang, You can’t post your php script code in the comment section here :-(

    Could you get on to our official forum and post it? So that we can take a look and possibly help you people ..thanks for understanding

  14. @Satish, I’ve uploaded the files on my server and tweak it to my database specifications. I solved the problem that I had, now whenever I press the submit button i get: “login failed” so I’m guessing that its the connection to my database is the problem now. The password field is hashed in my database so I think I’m going to have to find a way to get it back to its original form to compare it with the passwords from the textbox. Any thoughts on how to unhashed the password field in the database that I’m working with? NB:I wasn’t the one created the database.

  15. I just fetch the username alone from the database and i logged in successfully, so Its the hashed password was the problem why I got the login failed message.

Leave a Reply

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