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. @Odain, I had similar problem in my early days of PHP & MySQL programming :-)

    Technically, you can’t and shouldn’t unhash the password stored in the database, that would violate the security protocol.

    Solution: Once the user enters the password in the password field and submits it, let the script hash the user entered password and let this hashed password be compared with the hashed password present inside your database. SIMPLE!

    Example:
    Scenario: If you has md5 encrypted and stored the password in database.

    Now once the user enters password in login.php and passes it to processLogin.php

    you encrypt the user entered value:

    $password = md5($_POST[‘password’]);

    now compare this $password with the password fetched from the database.

    Hope it helps :-)


  2. @Satish, thanks for that info, anyways, i wasnt tryin to unhashed the password in the database, i just wanted a way to compare the password enterd by the user to the hashed password in the database, i was thinking about hashing the password entered by the user but i had some challenges due to the fact that i wasnt the 1 who developed the drupal website. I’m developin a new website using html5 along with php but i have an existing drupal site and i want the users on that site to be able to login to this new site i’m developing. I dnt knw if any1 of u guys have developed websites using drupal but I’m trying to use an alternative way: hook_auth method but not getting through. here is the sample code i got on the drupal website:

    function hook_auth($username, $password, $server) {
    if (variable_get(‘drupal_authentication_service’, 0)) {
    if (!$server) {
    $server = variable_get(‘drupal_default_da_server’, ”);
    }
    else if (variable_get(‘drupal_default_da_server_only’, 0)) {
    if (variable_get(‘drupal_default_da_server’, ”) != $server) {
    return;
    }
    }
    if (!empty($server)) {
    $result = xmlrpc(“http://$server/xmlrpc.php”, ‘drupal.login’, $username, $password);
    if ($result === FALSE) {
    drupal_set_message(t(‘Error %code: %message’, array(‘%code’ => xmlrpc_errno(), ‘%message’ => xmlrpc_error_msg())), ‘error’);
    }
    else {
    return $result;
    }
    }
    }
    }

    and here is what I’ve altered:

    xmlrpc_errno(), ‘%message’ => xmlrpc_error_msg())), ‘error’);
    }
    else {
    return $result;
    }
    }
    }
    }

    hook_auth($uname, $pass, $server);
    ?>

  3. here the adjustments, i made:

    xmlrpc_errno(), ‘%message’ => xmlrpc_error_msg())), ‘error’);
    }
    else {
    return $result;
    }
    }
    }
    }

    hook_auth($uname, $pass, $server);
    ?>

  4. Hi,
    Very useful tutorials you have made in PHP, really lived them.. But i have one little confusion here.. when i made logout page and after clicking the logout button . I am getting an error. like this

    Notice: Undefined index: userName in C:\wamp\www\logout.php on line 9
    Call Stack
    #TimeMemoryFunctionLocation
    10.0005367888{main}( )..\logout.php:0
    Successfully logged out!

    Can you Help me with this error//

    and i also wanna buy ur tutorials in php if u help in understanding it well

  5. hey. im having a trouble. i keep on getting this error, “Failed.You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ”’,”,”,”,”,”,”,)’ at line 1″

  6. @ryan, Use the same code and store user details. Pop the details once someone visits a page with his/her username. Do not use sessions, since it must also be visible to people who are not logged in.

    Ex:

    .com/profile.php?username=BillGates

    This would take people to BillGates profile info.

  7. Thanks for the tutorial, but I am having some issues getting the logout.php to work. It says that it logs out fine but comes up with an error message also. Notice: Undefined index: userName in C:\wamp\www\logout.php on line 9. The code is the same as above as I am just trying to teach myself some php. Any ideas why it would be doing this? I would appreciate it.

  8. @Jay, Use session_destroy();
    Comment session_unset(); and it must work. Look at previous commentators, they had same problem and they could solve it by using either session_destroy() or session_unset() , when both used together it shows error.

    Hope you had good time learning PHP :-)

  9. Satish,

    Could I know your gtalk/skype please? I’m learning PHP/MYSQL and some have problems that need to be addressed. I would be very thankful to you. I just wrote you through contact us page.

    Thanks
    Sam

  10. Hello Satish, its jay here cool tutorial help me a lot !! but hey could you help me with this code
    its my seach engine with php it works ok but i need to only display 10 messages per page an give my Visitors the option to click next for the next page bellow is the code
    Please help if you can

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    
    < ?php
    $button = $_GET ['submit'];
    $search = $_GET ['search']; 
     
    if(!$button)
    echo "you didn't submit a keyword";
    else
    {
    if(strlen($search)<=1)
    echo "Search term too short";
    else{
    echo "You searched for <b>$search <hr size='1'/>";
    mysql_connect("localhost","your mysql username","password");
    mysql_select_db("your database name");
     
    $search_exploded = explode (" ", $search);
     
    foreach($search_exploded as $search_each)
    {
    $x++;
    if($x==1)
    $construct .="keywords LIKE '%$search_each%'";
    else
    $construct .="AND keywords LIKE '%$search_each%'";
     
    }
     
    $construct ="SELECT * FROM searchengine WHERE $construct";
    $run = mysql_query($construct);
     
    $foundnum = mysql_num_rows($run);
     
    if ($foundnum==0)
    echo "Sorry, there are no matching result for <b>$search</b>.1. 
    Try more general words. for example: 
    If you want to search 'how to create a website' 
    then use general keyword like 'create' 'website'2. 
    Try different words with similar
     meaning3. Please check your spelling";
    else
    {
    echo "$foundnum results found !<p>";
     
    while($runrows = mysql_fetch_assoc($run))
    {
    $title = $runrows ['title'];
    $desc = $runrows ['description'];
    $url = $runrows ['url'];
     
    echo "
    <a href='$url' rel="nofollow"><b>$title</b></a><br />
    $desc<br />
    <a href='$url' rel="nofollow">$url</a></p><p>
    ";
     
    }
    }
     
    }
    }
     
    ?>
     
    </p>
  11. Hye there,

    Nice tutorial dude.

    But i have a question. I am planning to create a Dynamic website, where members will have

    to register themselves, and access their profile through a login form. I just want to know if

    the above login form is secure against all kinds of attacks that hackers can use to; gain

    control of other users accounts, delete accounts and/or change data like

    “SQL Injection attacks”,

    “Session Hijacking”,

    “Network Eavesdropping”,

    “Cross Site Scripting”,

    “Brute Force Attacks”, etc…

    simply any kind of attack from hackers. I know nothing is 100% secure, but i want something
    ALMOST 100% secure.

    Hope you will reply me as soon as possible.

    Thanks anyway Satish :)

    1. @sahil, It’s safe, if you can add little more things like: Adding mysql_real_escape_string() around all the user inputs.

      Check:
      Registration Form Using jQuery + PHP + AJAX (PART 1)
      Login Form: jQuery + PHP + AJAX

      I have added mysql_real_escape_string() in those video tutorials.

      For a membership site, I would recommend integrating WordPress, which is secure and keeps updating against latest security threats and most importantly it’s a OpenSource Software.

  12. hi i am try to this code some error is come out plz help for this

    Warning: mysql_connect() [function.mysql-connect]: Access denied for user ‘root’@’localhost’ (using password: NO) in /home/newtocli/public_html/db.php on line 2

    Warning: mysql_select_db(): supplied argument is not a valid MySQL-Link resource in /home/newtocli/public_html/db.php on line 3

    Warning: session_start() [function.session-start]: Cannot send session cache limiter – headers already sent (output started at /home/newtocli/public_html/db.php:2) in /home/newtocli/public_html/signin.php on line 4

    Warning: mysql_query() [function.mysql-query]: Access denied for user ‘newtocli’@’localhost’ (using password: NO) in /home/newtocli/public_html/signin.php on line 20

    Warning: mysql_query() [function.mysql-query]: A link to the server could not be established in /home/newtocli/public_html/signin.php on line 20

    Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource in /home/newtocli/public_html/signin.php on line 22

    1. @manoj, Since it’s not connected to the database, nothing will work.
      Make sure to create a database and table before you execute the script.

      Database creation, Table creation etc are also illustrated in our videos, so kindly follow along and it must work.

  13. I typed out the exact same code but I’m getting the following error:
    Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in C:\wamp\www\signin.php on line 22

    1. @priyanka, Separately run the MySQL query you have assigned to $sql. This way you can test your application for possible errors.

      Also look for any typos in the variable names.

      If nothing helps, post your code in our forum and I’ll go through it.

Leave a Reply

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