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.


Logic:-
1 – First we make signup or registration form to create username and password for login.
In Signup process we check if entered username is already existing in our database then we prompt error message else allow him to create an account.

2 – Now the Second step is creating your Login Page.
If user is registered then allow him to login into home page else prompt error message.

3 – If User is registered user i.e. username password exists in database then before redirecting him into home page we save his username in SESSION.
We use this SESSION variable in our home page to check whether user is logged in or not? If it is session variable is set then allow him to access the content of home page else redirect to login page.

4 – Last step is adding logout button. When user click on logout button we will unset or clear the session variable and redirect him to login page.


Files:-
1 – signup.php (Used for signup or registration process)
2 – login.php (Used for user login)
3 – home.php (User home page after login)
4 – logout.php (Used for logout purpose)
5 – config.php (Contain database connection code)
6 – style.php (For styling the pages)

Step 1:- Create a table “users” with the code below:
User table

CREATE TABLE IF NOT EXISTS `users` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `firstname` varchar(10) NOT NULL,
  `lastname` varchar(20) NOT NULL,
  `username` varchar(16) DEFAULT NULL,
  `password` char(50) DEFAULT NULL,
  `email` varchar(20) NOT NULL,
  `is_active` int(1) NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `username` (`username`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=18 ;



Step 2:- Create a config.php file and put below code in it.

<?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 and add below code in it.

Signup Page
Signup Page


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

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_name= mysql_real_escape_string($_POST['firstname']);
$last_name= mysql_real_escape_string($_POST['lastname']);
$username = mysql_real_escape_string(stripslashes($_POST['username']));
$password = mysql_real_escape_string(stripslashes(md5($_POST['password'])));
$mail = mysql_real_escape_string($_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.

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 (firstname,lastname,username,password,email,is_active) VALUES (‘”.$first_name.”‘,’”.$last_name.”‘,’”.$username.”‘,’”.$password.”‘,’”.$mail.”‘,’1′);”;
mysql_query($query);
echo “Thank You for Registration.”;
echo ‘<a href=”login.php”>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” class=”form-signup”>
<div id=”header”><h2 class=”sansserif”>Create an account</h2></div>
 <table>
    <tr>
      <td>Select Your Firstname:</td>
      <td> <input type=”text” name=”firstname” size=”20″ placeholder=”First name”><span class=”required”>*</span></td>
    </tr>

<tr>
      <td>Select Your Lastname:</td>
      <td> <input type=”text” name=”lastname” size=”20″ placeholder=”Last name”><span class=”required”>*</span></td>
    </tr>
 
    <tr>
      <td>Select Your Username:</td>
      <td> <input type=”text” name=”username” size=”20″ placeholder=”User name”><span class=”required”>*</span></td>
    </tr>
             
    <tr>
      <td>Select Your Password:</td>
      <td><input type=”password” name=”password” size=”20″ placeholder=”Password”><span class=”required”>*</span></td>
     </tr>
     
<tr>
      <td>Select Your Email:</td>
      <td> <input type=”text” name=”email” size=”20″ placeholder=”Email”><span class=”required”>*</span></td>
    </tr>
<tr>
       <td><input type=”submit” value=”Sign Up” class=”btn btn-large btn-primary”></td>
        
     </tr>
 </table>
</form>
</div>
</body>
</html>


Step 4:- Create “login.php” file with following code.

Login Page
Login page


<?php 
if(isset($_POST) && !empty($_POST))
{
session_start();
include(“config.php”); //including config.php in our file
$username = mysql_real_escape_string(stripslashes($_POST['username'])); //Storing username in $username variable.
$password = mysql_real_escape_string(stripslashes(md5($_POST['password']))); //Storing password in $password variable.


$match = “select id from $table where username = ‘”.$username.”‘ and password = ‘”.$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:home.php”);
// It is the page where you want to redirect user after login.
}
}else{
?>
<html>
<head>
<title>Login</title>
<link rel=”stylesheet” type=”text/css” href=”style.css” />
</head>
<body>
 <div class=”container login”>
<form action=”<?php $_SERVER['PHP_SELF'] ?>” method=”post” class=”form-signin” id = “login_form” >
<h2 class=”form-signin-heading”>Admin/Employee Login</h2>
<input type=”text” name=”username” size=”20″ placeholder=”Username”>
<input type=”password” name=”password” size=”20″ placeholder=”Password”></br>
<input type=”submit” value=”Log In” class=”btn btn-large btn-primary”>
<a href=”signup.php”>Sign Up</a>        
</form>
</div>
</body>
</html>
<?php
}
?>


Step 5:- Create “home.php” file with following code.

<?php
session_start();
if(isset($_SESSION['user']) && !empty($_SESSION['user'])){
echo “You are Welcome “. $_SESSION['user'];
?>
<a href = “logout.php”>Logout</a>

<?php
}else{
header(“location:login.php”);
}
?>


Step 6:- Create “logout.php” file with following code.

<?php 
session_start();
session_destroy();
header(“location:login.php”);
?>
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.

89 thoughts on “PHP Simple Login Form | PHP Tutorial for Beginners

    • 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.

    • 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.

  1. 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 :)

  2. 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.

  3. 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

  4. 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?

  5. 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. :)

    • 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

  6. 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

  7. error is coming while compiling login.php

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

  8. 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)

  9. 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

  10. 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:PROJECTxampplitehtdocslog_testlogin.php:1) in H:PROJECTxampplitehtdocslog_testlogin.php on line 2

    Warning: Cannot modify header information – headers already sent by (output started at H:PROJECTxampplitehtdocslog_testlogin.php:1) in H:PROJECTxampplitehtdocslog_testlogin.php on line 31

    Please help me. I am new in php.

    • 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.

    • 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:PROJECTxampplitehtdocslog_testlogin.php:1) in H:PROJECTxampplitehtdocslog_testlogin.php on line 30.

      Plz help me.

    • 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;

    • 2nd part

      } else {

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

      header(“location:admin.php”);

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

      }
      ?>

    • 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”); “.

    • 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:xampphtdocsworkingconfig.php:2) in C:xampphtdocsworkinglogin.php on line 28..
      My email is: sarach819@gmail.com

  11. HI,

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

    • 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

  12. 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.

  13. 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.

  14. when i am making script for reg. form for inserting values ,my submit is not working?? plz guide me n with whom i should header it?? reply

  15. I am getting an error
    Warning: mysql_num_rows() expects parameter 1 to be resource, boolean given in C:xampphtdocsCloudlogin.php on line 18
    please help me :((((

  16. I want to send email to user account for activation at the time of registration. I undestand I will have to generate activation code, url and use mail() function.Could you please confirm or provide your suggestion?

  17. we have receive an error after we try coding those codes above please send me email to fix this problem
    “Sorry, there is no username itsmecris16 with the specified password.Try again”

  18. Notice: Undefined variable: user in C:xampphtdocssimplesignup.php on line 14

    Warning: mysql_num_rows() expects parameter 1 to be resource, boolean given in C:xampphtdocssimplesignup.php on line 17
    Thank You for Registration.Click Here to login you account.

Leave a Reply

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

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>