PHP, MySQL, Drupal, .htaccess, Robots.txt, Phponwebsites: Login validation using php and mysql

6 Jul 2014

Login validation using php and mysql

                      Everybody should see the login pages in most of websites. You should have doubt about this login form, how they validate username and password. There is nothing, just only 2 steps as follows as for login validation using php.
                      1. You enter username and password already registered which is stored in mysql database.
                      2. After you submit a button to login, it check the database values whether the username and password is correct or not using php and mysql query. The mysql query for select a values from mysql database as like this:
             
             ie, SELECT * FROM table_name WHERE name='username' and password='password' 

If it return values correctly, then you can login. Otherwise it give error message.

Simple login validation using php and mysql: 


                      Lets see how to validate the username and password using php.
                      1. First you create table using mysql query like this:

           CREATE TABLE login(name varchar(30), password varchar(30), PRIMARY KEY(name))

Now the table 'login' is created. The field 'name' is primary key. Because the username must be unique.
                      2. Then insert values into table using  mysql query like this:

           INSERT INTO login VALUES('guru','guru') 

Now the table look like this:

login validation using php

                       3. The php script for login validation as follows as:
login.php:

<html>
<head>
<style type="text/css">
 input{
 border:1px solid olive;
 border-radius:5px;
 }
 h1{
  color:darkgreen;
  font-size:22px;
  text-align:center;
 }
</style>
</head>
<body>
<h1>Login<h1>
<form action='#' method='post'>
<table cellspacing='5' align='center'>
<tr><td>User name:</td><td><input type='text' name='name'/></td></tr>
<tr><td>Password:</td><td><input type='password' name='pwd'/></td></tr>
<tr><td></td><td><input type='submit' name='submit' value='Submit'/></td></tr>
</table>

</form>
<?php
session_start();
if(isset($_POST['submit']))
{
 mysql_connect('localhost','root','') or die(mysql_error());
 mysql_select_db('new') or die(mysql_error());
 $name=$_POST['name'];
 $pwd=$_POST['pwd'];
 if($name!=''&&$pwd!='')
 {
   $query=mysql_query("select * from login where name='".$name."' and password='".$pwd."'") or die(mysql_error());
   $res=mysql_fetch_row($query);
   if($res)
   {
    $_SESSION['name']=$name;
    header('location:welcome.php');
   }
   else
   {
    echo'You entered username or password is incorrect';
   }
 }
 else
 {
  echo'Enter both username and password';
 }
}
?>
</body>
</html>


        Where,
                if(isset($_POST['submit']){}    means run after submit a results.
                if($name!=''&&$pwd!=''){}   means if either username or password is empty, it give message like as 'Enter both username and password'.
                mysql_query("select * from login where name='".$name."' and password='".$pwd."'  ")      select the values if the username and password is present.
                $res=mysql_fetch_row($query) return row as numeric array.
You don't know about mysql_fetch_row, then visit mysql-fetch-row in mysql.
               if($res){} validate the result. If it is correct, then your name is stored in session variable and also you'll navigate to 'welcome.php' page. Otherwise you'll get 'You entered username or password is incorrect' message. You want to visit Session in php.
              When you run the above file, it should be like this:

login form in html and php
             
               The php script for welcome page:

 welcome.php:


<?php    
         session_start();
         $name=$_SESSION['name'];    
         echo'welcome :'. $name.'<br>';
         echo'<a href="signout.php">Signout</a>';
?>

      
             Now you enter username and password  'guru' and 'guru', you will navigate to 'welcome.php' page and get output like this:

                   welcome: guru
                   Signout

 If it is wrong, then you can't login.


Signout in php:              


            When you click the signout.php, it destroy the session and return back to login page. The php script for signout page:
signout.php:

<?php    
         session_start();
         session_destroy();
         header('location:login.php');
?>

                session_destroy is used to destroy the session variable in php.

Related Post:
Create Registration form using PHP and MySQL
Login form validation with remember function using php and mysql
Forgot password to mail in login form validation using PHP and Mysql

58 comments:

  1. how to define database and table ? thanks

    ReplyDelete
    Replies
    1. To know about how to create database, table and resgsitration form, visit http://www.phponwebsites.com/2014/07/php-mysql-create-registration-sign-up-form.html

      Delete
    2. Hello, your coding is great but i got this error "Notice: Undefined variable: name in C:\xampp\htdocs\testThis\welcome.php on line 4" when i tried to run the program

      Delete
    3. you need to use error_reporting('E_ALL ^ E_NOTICE');
      top of your welcome.php page

      Delete
    4. Thank you for your reply, i added it just now and the other problem appear.. the $name cannot be called. the output is just "welcome"

      Delete
    5. Sorry,
      You need to use $name = $_SESSION['name']; at welcome.php
      I changed now. Please check it.

      Delete
    6. it fixed now.. thank you so much ^^

      Delete
  2. hello guru, do u mind if i ask u a favor? i am doing my final project for my last semester and i need some help..

    ReplyDelete
  3. thanks alot, its working fine

    ReplyDelete
  4. When i hit submit button ,it is showing php code on other tab .wat to do now? pls help me

    ReplyDelete
    Replies
    1. The problem is the format of your welcome.php page may be false. Please paste your code within "" tag.

      Delete
  5. Unknown column 'password' in 'where clause' why does it keeps saying this

    ReplyDelete
  6. Please check your table structure whether your table contains "password" column

    ReplyDelete
  7. Thanks guru ji, ur tutorial is realy held full for me ,
    I have a question, i m trying to solve it from 3 days but i m failed
    ,,
    how to show all colums of one user from table

    welcome: guru

    hence , Now i need to give information of user in same manner

    welcome: guru
    first_name:
    last_name :
    etc

    please solve my problem thanks
    as u have posted Name ,

    ReplyDelete
    Replies
    1. select * from user where name="username"

      Delete
  8. Warning: Cannot modify header information - headers already sent by (output started at /Users/J/Sites/login.php:2) in /Users/J/Sites/login.php on line 44

    i get this error what shld i do

    ReplyDelete
  9. Then you will try to use below code instead of " header('location:welcome.php');"

    The php code is:

    echo "<script> window.location.href='welcome.php'; </script>";

    ReplyDelete
    Replies
    1. Parse error: syntax error, unexpected '"' in C:\xampp\htdocs\login.php on line 32

      Delete
  10. i want to redirect the page if they have entered wrong uid

    ReplyDelete
    Replies
    1. You need to write redirect code instead of displayed message "You entered username or password is incorrect"

      Delete
  11. hello i did the code

    ';
    echo'Signout';
    ?>



    but i only get welcome:
    with no name.. how do i fix this?

    ReplyDelete
  12. How to debug this warning
    Warning: session_start() [function.session-start]: Cannot send session cache limiter - headers already sent (output started at C:\xampp\htdocs\mypage\login.php:25) in C:\xampp\htdocs\mypage\login.php on line 26

    Warning: Cannot modify header information - headers already sent by (output started at C:\xampp\htdocs\mypage\login.php:25) in C:\xampp\htdocs\mypage\login.php on line 40

    ReplyDelete
  13. Guru ji how to create publish / unpublish function in core php

    ReplyDelete
  14. like that wordpress / joomla publish / unpublish function.

    ReplyDelete
  15. This comment has been removed by the author.

    ReplyDelete
  16. thanku guruji..awsome codefor me

    ReplyDelete
  17. how do u include maps in your code?

    ReplyDelete
    Replies
    1. First Download map iframe code and put into your php code and then run

      Delete
  18. very helpful this code, how can I add regex, for exple minimum 8 char, at least 2 digit and one of special (@, $, &, _, #)?

    ReplyDelete
  19. Hi guru,i am doing login page for particular user can access particular thing only,for example Region A,B,C an every user belongs to particular region (from id 100-103 A region),(104 to 106 B region) if suppose B region id(105) enter into A region it will show invalid credential give some idea

    ReplyDelete
  20. how to upload more then 5MB size pdf fileupload And store data base in pdf file location in php ??pls helpin vaildate replay

    ReplyDelete
    Replies
    1. Please refer this: http://www.phponwebsites.com/2014/10/php-mysql-upload-images-to-database.html

      Delete
  21. i try to run your code but their is error at line 29(mysql_connect('localhost','root','') or die(mysql_error());) say not defind how can i fix it
    thank you!

    ReplyDelete
  22. i try to run your code but their is error at line 29(mysql_connect('localhost','root','') or die(mysql_error());) say not defind how can i fix it
    thank you!

    ReplyDelete
    Replies
    1. This is the database connection part. Please verify your db connections.

      Delete
  23. can you help me?

    ReplyDelete
  24. hi mr guru.plz mr help me when i hit login btn i get the error sms like this.how to resolve this problem.

    "You entered username or password is incorrect"

    ReplyDelete
    Replies
    1. I think, you've entered wrong username and password.

      Delete
  25. This comment has been removed by the author.

    ReplyDelete
  26. SHALL i have to changea root with my databse address while connecting data in this code tomysql_connect('localhost','root','') or die(mysql_error());

    ReplyDelete

  27. Warning: session_start() [function.session-start]: Cannot send session cache limiter - headers already sent (output started at C:\xampp\xampp\htdocs\displaydata\d12.php:25) in C:\xampp\xampp\htdocs\displaydata\d12.php on line 26

    ReplyDelete
  28. hi
    i have one small doubt can you please solve it

    ReplyDelete
  29. Notice: Undefined index: name in G:\Xampp\htdocs\login_vis\welcome.php on line 3
    welcome :
    Signout

    ReplyDelete
    Replies
    1. error_reporting('E_ALL ^ E_NOTICE');
      on top of welcome.php code

      Delete
  30. ';
    echo'Signout';
    ?>

    please have a look into this once. i am getting this issue

    ReplyDelete
  31. session is not working!!!
    plzzzzz help

    ReplyDelete
  32. i found this error how can i resolve it...
    Parse error: syntax error, unexpected '$res' (T_VARIABLE) in C:\xampp\htdocs\salt1\code1.php on line 8

    ReplyDelete
  33. Awesome thanks for your post. I did an iteration of this before but PHP deprecated a function that I used Anyway when I destroy the session I can simply hit back and can access the welcome.php page. How do you protect against that?

    ReplyDelete
  34. Thank you. found a good tutorial after a lot of searching!

    ReplyDelete
  35. when i enter a user name and password it shows fllowing:Access denied for user 'root'@'localhost' (using password: NO)
    i have given correct root password so what should i do

    ReplyDelete
    Replies
    1. There is a problem on your mysql connection

      Delete
  36. @guru : am not able to link to welcome.php page

    ReplyDelete
  37. Such a very useful article. Very interesting to read this article.I would like to thank you for the efforts you had made for writing this awesome article. SKYWESTONLINE login

    ReplyDelete