Monday, 15 October 2012

PHP Simple Login Form | PHP Tutorial for Beginners

PHP Login Form or Login Script in PHP!!!

If you know how to create website in php and you started creating any php web site that allow user or admin to login then first thing comes in your mind is to create php login script or login form in php that allow user or admin to get login. For login the user must have their respective username and password which he enters in to login form page. To make his successful login we verified his username and password with MySQL database table which contain the username and password for all.

In this tutorial of php code for beginners we will show you step by step creation of your first php login form or php script for login. Basically we create one simple login form in html and connect this code with MySQL database and php script.

You can also use the JavaScript validation or jquery validation for your login php form.



Step 1:- Create a table "users" with the code below:

CREATE TABLE users(
  id int NOT NULL AUTO_INCREMENT,
  username varchar(16),
  password char(16),
  PRIMARY KEY(id),
  UNIQUE (username)
)

Step 2:- Create a config.php file with the below:

<?php
$database = "mydata";  // the name of the database.
$server = "localhost";  // server to connect to.
$db_user = "root";  // mysql username to access the database with.
$db_pass = "";  // mysql password to access the database with.
$table = "users";    // the table that this script will set up and use.
$link = mysql_connect($server, $db_user, $db_pass);
mysql_select_db($database,$link);
?>

Step 3:- Create "signup.php" file with following code:

<?php
include("config.php"); 
//including config.php in our file

if(!empty($_POST['username']) && !empty($_POST['password'])){
// Now checking user name and password is entered or not.

$user = $_POST['username'];
$pass = $_POST['password'];
$check = "SELECT * from users where username = '".$user."'";
$qry = mysql_query($check);
$num_rows = mysql_num_rows($qry); 

if($num_rows > 0){
// Here we are checking if username is already exist or not.

echo "The username you have entered is already exist. Please try another username.";
echo '<a href="signup.php">Try Again</a>';
exit;
}

// Now inserting record in database.
$query = "INSERT INTO users (username,password) VALUES ('".$user."','".$pass."');";
mysql_query($query);
echo "Thank You for Registration.";
echo '<a href="register.html">Click Here</a> to login you account.';
exit;
}

?>
<html>
<head>
<title>Registration Page | Simple login form</title>
<link rel="stylesheet" type="text/css" href="style.css" />
</head>
<body>
<div id="containt" align="center">
<form action="<?php $_SERVER['PHP_SELF']?>" method="post">
<div id="header"><h2 class="sansserif">User Registration</h2></div>
 <table>
             
    <tr>
      <td>Select Your Username:</td>
      <td> <input type="text" name="username" size="20"></td>
    </tr>
             
    <tr>
      <td>Select Your Password:</td>
      <td><input type="password" name="password" size="20"></td>
     </tr>
     <tr>
       <td><input type="submit" value="Sign Up"></td>
        
     </tr>
 </table>
</form>
</div>
</body>
</html>


Step 4:- Create "register.html" file with following code:

<html>
<head>
<title>Php Simple Login Form</title>
<link rel="stylesheet" type="text/css" href="style.css" />
</head>
<body>
<div id="containt" align="center">
<form action="login.php" method="post">
<div id="header"><h2 class="sansserif">Admin/Employee Login</h2></div>
 <table>
             
        <tr>
            <td>Enter Username:</td>
            <td> <input type="text" name="username" size="20"></td>
        </tr>
             
        <tr>
            <td>Enter Password:</td>
            <td><input type="password" name="password" size="20"></td>
        </tr>
        <tr>
             <td><input type="submit" value="Log In"></td>
             <td><a href="signup.php">Sign Up</a></td>
        </tr>
 </table>
</form>
</div>
</body>
</html>

Step 5:- Create "login.php" file with following code:

<?php 
session_start();
include("config.php"); //including config.php in our file
$username = $_POST["username"]; //Storing username in $username variable.
$password = $_POST["password"]; //Storing password in $password variable.


$match = "select id from $table where username = '".$_POST['username']."'
and password = '".$_POST['password']."';"; 

$qry = mysql_query($match);

$num_rows = mysql_num_rows($qry); 



if ($num_rows <= 0) { 

echo "Sorry, there is no username $username with the specified password.";

echo "Try again";

exit; 

} else {



$_SESSION['user']= $_POST["username"];

header("location:admin.php");

// It is the page where you want to redirect user after login.

}
?>

Step 6:- Last step is Create "admin.php" file with following code:


<?php
session_start();
echo "You are Welcome ". $_SESSION['user'];

// You can place here the actual test or images you want to show. I have just added welcome message.
?>

Now your PHP login form is ready to use.

Hope this php tutorial is useful for you. Keep following Php Tutorials For Beginners for more help.

79 comments:

  1. great
    good working very well
    thanks bro

    ReplyDelete
  2. its only redirecting me in login.php, possible problems?

    ReplyDelete
    Replies
    1. Because may be you have error in your username or password.

      Delete
  3. Thanks for the information , because i'm still beginner about php code . by the way which one is login processing ?

    ReplyDelete
    Replies
    1. login.php is for your login processing.

      Delete
    2. Thanks on your marvelous posting! I certainly enjoyed reading it, you will be a great Author. I will remember to bookmark your blog and will eventually come back from now on. I want to encourage that you continue your great writing, have a nice day!

      Delete
  4. Thank you very much really very helpful for me Free Register Login Code

    ReplyDelete
  5. How do i use the Sessions info to control access to other pages?

    ReplyDelete
    Replies
    1. In above post i have used $_SESSION['user'] to store user name after successful login. On target page(in our case 'admin.php') use can use this session info to show Welcome message to the user.
      To now more on session variable see this post PHP Session Example and PHP Session Tutorial

      Delete
  6. How do users register?

    ReplyDelete
  7. Hey there. Have set this up perfectly, and it works really well! Thank you. However, how can I restrict the access to my pages unless user is logged in?

    ReplyDelete
  8. nice post .....
    thanks :)

    ReplyDelete
  9. how to use this code to separate admin and user??

    ReplyDelete
    Replies
    1. To seperate admin and user, you have to set some field in database during new registration process. The registration form contain drop down field to choose "admin" or "user" register.

      Delete
    2. How to direct the user to adminlogin.php if they login as admin and to login.php page if they login as user only. Where the code must be written? in login.html or login.php?
      Thank you.

      Delete
  10. how user register in the same

    ReplyDelete
    Replies
    1. I have not included registration code in this example. But sure i will update this code with registration process in this weekend.

      Delete
  11. my database not connected.. plz help

    ReplyDelete
    Replies
    1. Check your database name is "mydata" or not?

      Delete
  12. when i log.in always say there is no username admin with the specified password. newbie :)

    ReplyDelete
  13. Nice artical keep on writing for PHP beginner
    jobs in burdwan

    ReplyDelete
  14. Great job my friend, the code is very understandable!
    But I have one question.When I run my page through my localhost I get this result "Sorry, there is no username with the specified password.Try again" directly, without inserting an account into my form.Do you have any ideas?

    *sorry about the previous post but I had forgotten smothing :)

    ReplyDelete
  15. This is because I have not created user registration page here and sorry for that. In above example only those person can login whose data is available in database.
    I will make user registration page also as soon as i get the time.

    ReplyDelete
  16. please please please make the registration page soon, i really need it. thank you

    ReplyDelete
    Replies
    1. I have added the code for "User Sign Up". Please check.

      Delete
  17. 0) { // Here we are checking if username is already exist or not echo "The username you have entered is already exist. Please try another username."; echo 'Try Again'; exit; } // Now inserting record in database. $query = "INSERT INTO users (username,password) VALUES ('".$user."','".$pass."');"; mysql_query($query); echo "Thank You for Registration."; echo 'Click Here to login you account.'; exit; } ?> why this message appear to me in the signup screen

    ReplyDelete
    Replies
    1. May be you have missed php starting tag ie <?php

      Delete
  18. Great work, thank you very much!
    Only one question about the signup.php: i keep getting an error about $_server being an undefined variable... where is it defined? I didn't get that part, what am I doing wrong?

    ReplyDelete
    Replies
    1. Just turn off your warning form php.ini file.

      Delete
    2. It was my bad actually. I wrote it exactly like in your example $_server['php_self'] when it has to be written with CAPS: $_SERVER['PHP_SELF'] otherwise it won't work.

      Delete
  19. very informative.I new to php. Can i get of example of upload file and download uploaded file php code. I am doing simple Online storage.looking forward to your feedback. :)

    ReplyDelete
    Replies
    1. Thanks...
      Here is a link for file downloading in php
      File Downloading in PHP

      Delete
  20. Hello again, thank you for updating the code!!
    I have some questions: First of all I have added 3 additional fields in my database(firstname,lastname,email) and I haven't created the html file, because i'm using the form inside the login.php file.When I'm inserting a new user in my database the message tells me that it is successfull, but there is no new record in the databse.Also when I'm accessing the login page this message appears without inserting anything in my form"Sorry, there is no username with the specified password.Try again" and I don't know why.
    Thank you In advance!!!.

    ReplyDelete
    Replies
    1. Can you show me your code? It will be easy for me to find your issue.

      Delete
    2. Here is the code, also today I changed the code to check if all the fields are filled and now the previous message does not apear. 0){
      // Here we are checking if username is already exist or not.

      echo "The username you have entered is already exist. Please try another username.";
      echo 'Try Again';
      exit;
      }

      // Now inserting record in database.
      $query = "INSERT INTO users (firstname,lastname,username,password,email) VALUES ('".$first."','".$last."','".$user."','".$pass."".$mail."');";
      mysql_query($query);
      echo "Thank You for Registration.";
      echo 'Click Here to login you account.';
      exit;
      }

      ?>

      Delete
    3. if(!empty($_POST['username']) && !empty($_POST['password']) && !empty($_POST['firstname']) && !empty($_POST['lastname'])
      && !empty($_POST['email'])){
      // Now checking user name and password is entered or not.
      $first= $_POST['firstname'];
      $last= $_POST['lastname'];
      $user = $_POST['username'];
      $pass = $_POST['password'];
      $mail = $_POST['email'];
      $check = "SELECT * from users where username = '".$user."'";
      $qry = mysql_query($check);
      $num_rows = mysql_num_rows($qry);

      if($num_rows > 0){
      // Here we are checking if username is already exist or not.

      Delete
    4. You have syntax error in your sql query near '".$pass."".$mail."'. Try to replace with this:-
      $query = "INSERT INTO users (firstname,lastname,username,password,email) VALUES ('".$first."','".$last."','".$user."','".$pass."','".$mail."');";

      Delete
    5. Thank you for answering,
      I changed the thing that you mentioned,nothing happend.I still try to submit my data, but again there is no new record in my database.

      Delete
    6. Check out your database table fields similar as "firstname,lastname,username,password,email".

      Delete
    7. Thanks a lot!! you were right, I had a minor spelling mistake in the email field and I didn't even notice it when I was checking it due to the frustration.I also have a second question about the login page.This message appears to directly when I'm accessing the page"Sorry, there is no username with the specified password.Try again",do you have any ideas?
      Thank you again!

      Delete
  21. Thanks, this code was very useful...

    ReplyDelete
  22. Thanks a lot

    ReplyDelete
  23. hi are you there MR.Anil gupta?

    ReplyDelete
  24. can you add header?

    ReplyDelete
  25. hey how and where i save this table in 1st point

    ReplyDelete
    Replies
    1. Go into "phpmyadmin", create database called "mydata".
      After the click on SQL tab and paste the 1st point code and click on "Go" button. Your "User" table will get created

      Delete
  26. As I am a beginner in php so don't know much and want to make a login form in php
    so please let me know how to save this table

    ReplyDelete
  27. error is coming while compiling login.php

    SCREAM: Error suppression ignored for
    ( ! ) Notice: Undefined index: username in C:\wamp\www\login.php on line 4
    Call Stack
    # Time Memory Function Location
    1 0.2400 368896 {main}( ) ..\login.php:0

    ReplyDelete
  28. Hey sorry for the previous comment
    it is now working well
    thank you so much
    :)

    ReplyDelete
  29. Hello i have done everything as posted but i still get this message:

    Warning: session_start() [function.session-start]: Cannot send session cookie - headers already sent by (output started at /srv/disk3/1447904/www/racer.co.nf/login.php:1) in /srv/disk3/1447904/www/racer.co.nf/login.php on line 2

    Warning: session_start() [function.session-start]: Cannot send session cache limiter - headers already sent (output started at /srv/disk3/1447904/www/racer.co.nf/login.php:1) in /srv/disk3/1447904/www/racer.co.nf/login.php on line 2

    Warning: Cannot modify header information - headers already sent by (output started at /srv/disk3/1447904/www/racer.co.nf/login.php:1) in /srv/disk3/1447904/www/racer.co.nf/login.php on line 31


    why is this? (ps thank you so much)

    ReplyDelete
  30. how do i display the user who is logged in? and put it on a page?

    ReplyDelete
    Replies
    1. Can you please elaborate exactly what you need?
      1- Number of user online or
      2- Current user online.

      Delete
    2. number of users online

      Delete
  31. hey how do i make a button 'register' in the form so as admin get a mail about this registration

    ReplyDelete
    Replies
    1. In signup page after clicking on submit just call mail() function which contain user filled details.
      Here is a post for mail() function in Php.
      Sending Mail in Php

      Delete
  32. i keep getting this message when i run this code:

    Warning: mysql_num_rows() expects parameter 1 to be resource, boolean given in /srv/disk3/1447904/www/racer.co.nf/signup.php on line 12

    ReplyDelete
  33. Hi, after register when i am going to login browser send me a error

    Warning: session_start() [function.session-start]: Cannot send session cache limiter - headers already sent (output started at H:\PROJECT\xampplite\htdocs\log_test\login.php:1) in H:\PROJECT\xampplite\htdocs\log_test\login.php on line 2

    Warning: Cannot modify header information - headers already sent by (output started at H:\PROJECT\xampplite\htdocs\log_test\login.php:1) in H:\PROJECT\xampplite\htdocs\log_test\login.php on line 31


    Please help me. I am new in php.

    ReplyDelete
    Replies
    1. I think you have used "session_start()" twice in the page.
      if you have included "session_start()" in main header then don't write it on login.php page or any other content page, because header will automatically included in all pages.

      Delete
    2. Thanks Anil Gupta for ur reply. After removing "session_start()"
      it warned me

      Warning: Cannot modify header information - headers already sent by (output started at H:\PROJECT\xampplite\htdocs\log_test\login.php:1) in H:\PROJECT\xampplite\htdocs\log_test\login.php on line 30.

      Plz help me.

      Delete
    3. Can you show me your login.php code?

      Delete
    4. 1st part
      <?php
      include("config.php"); //including config.php in our file
      $username = $_POST["username"]; //Storing username in $username variable.
      $password = $_POST["password"]; //Storing password in $password variable.


      $match = "select id from $table where username = '".$_POST['username']."'
      and password = '".$_POST['password']."';";

      $qry = mysql_query($match);

      $num_rows = mysql_num_rows($qry);



      if ($num_rows <= 0) {

      echo "Sorry, there is no username $username with the specified password.";

      echo "Try again";

      exit;

      Delete
    5. 2nd part

      } else {



      $_SESSION['user']= $_POST["username"];

      header("location:admin.php");

      // It is the page where you want to redirect user after login.

      }
      ?>

      Delete
    6. Write at the beginning of your file and check.

      Delete
    7. Bro.. i'v write full login.php part1 & part2. plz check the error.
      It save data in database, check username & password but dont login. it called error in line 31 which is

      " header("location:admin.php"); ".

      Delete
    8. Make sure that "session_start()" is first line on your page.

      Delete
    9. please ensure that there is nothing before session_start() command. Even a white space before the session_start() command will generate this warning message.

      Delete
    10. sir i have same problem...plz help me what is should do...i have this error
      Warning: Cannot modify header information - headers already sent by (output started at C:\xampp\htdocs\working\config.php:2) in C:\xampp\htdocs\working\login.php on line 28..
      My email is: [email protected]

      Delete
  34. HI,

    Please, PLEASE do not publish tutorials, where anything goes to database without being sanitized. SQL Injection all the way.

    ReplyDelete
    Replies
    1. Thanks man for your comment, but this tutorial is for beginners who face difficulties during creation of their first login form.
      I have also created tutorial in my blog for preventing SQL INJECTION. Here is the link of that.
      Preventing SQL Injection

      Delete
    2. It's great that there is a tutorial for that too. But why leave the most important part away from the beginners? As information security is really a key part of every web application and therefore that's a first thing to learn before connecting anything to a DB

      Delete
  35. Hi man, thanks for sharing this.

    ReplyDelete
  36. Thank you very much! It's so helping me! But I think there's a fatal error on signup.php

    you can't use HTML tag ini PHP file unless you use echo ini it, even if I use it there will be a lot of problems following it. So I create 2 file named signup.php and signup.htm where I fill the signup.php with the PHP tags and the htm one with HTML tags and I add the code in signup.htm with include("signup.php");

    I hope it will help.

    ReplyDelete
  37. Your teaching procedure is very very good I have learnt a log please keep continue to do more for us

    ReplyDelete
  38. the if statements are not working :(

    ReplyDelete
  39. I *really* hate tutorials like this being around on the web. It is just irresponsible to keep it around. The fact that it is aimed at beginners is even worse and certainly not an excuse. Beginners have no idea you give them vulnerable code.

    When quickly glancing at the code I can see the following (without even digging deep into the code) :

    - It uses a deprecated database API (when you wrote this it wasn't, but at the time there were already better alternatives around).
    - It is vulnerable to SQL injection attacks
    - It stores plain text passwords
    - It is vulnerable to XSS attacks

    Having resources like this around is just a proper dick move and is the #1 reason there are soo many vulnerable applications out there in the wild. People who are looking for information on how to create a login with PHP have no idea what is wrong with the above tutorial and implement it without knowing their application is wide open for attackers!

    Just look at all the comments on here and even on Stack Overflow (http://stackoverflow.com/questions/17907822/php-login-error).

    So I ask you: please take your responsibility and either take this tutorial down, add a big fat banner stating this should *never* be used in production because it contains huge security holes or fix all the issues in the code.

    If for whatever reason you need / want help fixing the issues in the code or want to rewrite the entire thing and you need guidance you may contact me at my nickname @php.net. But whatever you choose this tutorial in its current state should simply not exist.

    ReplyDelete