PHP Scripts – WordPress Tutorials

Very first question in every one’s mind is “Why to use PHP Login Script ?”, The reason is that you might need a login authentication from some of your users, depending on your application to restrict their rights(what they can do and what they can’t).

If i have to save my data from non-authenticated people then all i need to do is to create a login page to save my data from  non-serious users.

Let us move to the development phase. I have to create following files:

  • login_form.php
  • login.php
  • success.php
  • logout.php

I will follow some important steps to complete this tutorial:

  1. Take some Input from User(userName, Password)
  2. Hit submit button, to send this data to the server
  3. Match the user input with the Data Base entries
  4. At this step i have two possibilities
  • If data matches then redirect user to success page
  • if data does not matches then ask User to Re-Enter the information

First i need to create a table that contains three fields (admin_id,admin_usr_name,admin_password)

After creating a table, i have inserted two values into it using the following Query

I got this Table

Let us create a Form to take input from user as i have shown in the following image:

login_form.php

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
<html>

<body>
<table width="200" border="0" cellspacing="1" align="center">
<form id="form1" name="form1" method="post" action="login.php">
<tr>
<td colspan="2"><h2>Members Login</h2></td>
</tr>
<tr>
<td>UserName:</td>
<td>
<input type="text" name="username" id="username" />

</td>
</tr>
<tr>
<td>Password:</td>
<td><input type="password" name="password" id="password" /></td>
</tr>
<tr>
<td colspan="2" align="center">
<input type="submit" name="btnSubmit" id="btnSubmit" value="Log In" />

</td>
</tr>
</form>
</table>
</body>

</html>

Now we have to create a login Script that will be executed on Server.

login.php

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
//*********Server Information to establish a connection ******

$host = 'localhost'; // Server Host Name
$user = 'root'; // Server User Name
$password = 'vertrigo'; // Server Password
$db = 'dbsneaker'; // Your Database

$link = mysql_connect($host,$user,$password) or die('Error in Server information');
mysql_select_db($db,$link) or die('Can not Select Databasse');

//***************End Connection Establishment***************************************
//*******Form Information********

$userName = mysql_real_escape_string($_POST['username']); //User Name sent from Form
$password = mysql_real_escape_string($_POST['password']); // Password sent from Form

//*********retrieving data from Database**********

$query = "select * from tbladmin where admin_usr_name='$userName' and admin_pwd='$password'";

$res = mysql_query($query);

$rows = mysql_num_rows($res);

//**********if $userName and $password will match database, The above function will return 1 row

if($rows==1)

//***if the userName and password matches then register a session and redrect user to the Successfull.php
{
$_SESSION['userName'];
$_SESSION['password'];
header("location:success.php");
}
else
{
echo 'Data Does Not Match &lt;br /&gt; Re-Enter UserName and Password';
}

&nbsp;

?&gt;

Now once this is executed , I need to create a success message and to display this success message i have to create a success.php Script

success.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
session_start();
if($_SESSION['userName']!='')
{
header("location:login_form.php");

}
else
{
echo '<h2>Successfully Login <br /> Welcome '.$_SESSION['userName'].'</h2>';

echo '<a href="logout.php"> Log Out</a>';
}

&nbsp;

?>

NOw its important to destroy the registered session and to destroy this session, I have created a logout script.

logout.php

1
2
3
4
5
6
7
8
<?php
session_start();
//*****session_destroy() will destroy the session
session_destroy();

header("location:login_form.php");

?>

If you find any kind of error, then please comment and ask me to solve that so that i can make this script perfect. It will rejoice me and make me confident. Feel free to comment.

Random Posts


Categories: PHP, Web Development
  • Pingback: Registration Form PHP Script :

    • http://none Amrita Singh

      Data Does Not Match
      Re-Enter UserName and Password

      this error shows even if data is matched with database

      • http://www.computersneaker.com/ Mudasir Nazir

        Please do have a look at your query carefully, there is some error in your query. Just put echo before your query to let you know what is actually being passed to your server.

  • deep

    fine script. But it should one step more to secure password. sql injection is possible in this method.

    • http://www.computersneaker.com/ Mudasir Nazir

      On your behalf, I will update the script dear. I have posted this script for the beginners and i would love if someone appreciate me with the feedback. You have strong point, that you shed light on my blog,So i will update the script.
      Have you checked my previous post that is Registration Form with PHP , I have used password security in that.

  • sachin

    ossum…dude..!!!

  • http://www.fb.com/evosoft.designs Syed Danish ALi

    brother iam having problem in log in success or in log in form the error is
    Notice: Undefined index: username in C:\xampp\htdocs\test\login.php on line 18

    Notice: Undefined index: password in C:\xampp\htdocs\test\login.php on line 19

    Warning: mysql_num_rows() expects parameter 1 to be resource, boolean given in C:\xampp\htdocs\test\login.php on line 29
    Data Does Not Match
    Re-Enter UserName and Password
    eben the password and user name is correct

    • http://www.computersneaker.com/ Mudasir Nazir

      You are required to check your field names from database, you have to confirm if they were as “username” and “password”. If both are true, Now come to HTML section of your script. Confirm that field names were same as database names were(“This is not rule, I am asking you because you are felt to be the beginner”). You might have some problems here. Fix them and then test your script.
      NOTE: username (“engrmudasir”) and Password(“1234560″) should exist in database values.

  • satyam

    i am unable to process your code on system .it give the error .

    • http://www.computersneaker.com/ Mudasir Nazir

      can you please mention that error here.

      • ayesha

        assalam o alaikum..its a bit easy code but i am confused in variables being passed from login form to login page..my database fields are id,name and password..my database is ‘login’ and database table is ‘logintable’ can you please help me to figure out where i have to make changes in the code?

        • ayesha

          the error is :
          Warning: mysql_num_rows() expects parameter 1 to be resource, boolean given in C:\xampp\htdocs\login.php on line 29
          Data Does Not Match
          Re-Enter UserName and Password

        • http://www.computersneaker.com/ Mudasir Nazir

          you just need to change the name of the database to ‘login’ and in your query it would be like SELECT * FROM logintable; SO you just need to change the query actually.

          • ayesha

            thank you so much i figured it out easily

      • amarjit prasad

        Warning: session_register() [function.session-register]: Cannot send session cache limiter – headers already sent (output started at C:\xampp\htdocs\loginvalidation\login.php:2) in C:\xampp\htdocs\loginvalidation\login.php on line 14

        Warning: Cannot modify header information – headers already sent by (output started at C:\xampp\htdocs\loginvalidation\login.php:2) in C:\xampp\htdocs\loginvalidation\login.php on line 16

        • http://www.computersneaker.com/ Mudasir Nazir

          You need to remove all the blank spaces in your page before HTML, and one more thing is to add ‘ob_start();’ at the start of your page right after session_start();
          Actually this error is because of white spaces in your HTML pages.

  • http://damiengrass.com Damien

    You need to secure your code more. This is again prone to a lot of vulnerabilities.

    In your register script, you were using MD5(). Use crypt instead…

    $salt = ‘$2a$07$R.gJb2U2N.FmZ4hPp1y2CN$’;
    crypt(“YourPasswordHere”, $salt);

    Also, never trust user input, you can use functions such as filter_var() to help sanitize data. I’d also recommend using mysql_real_escape_string() or even better, switching to PDO and making full use of it’s parameter binding.

    I lot more issues are in the script, too. Secure your output for a start.

    • http://damiengrass.com Damien

      Also, session_register() and session_is_registered() has been deprecated and removed as of PHP 5.4.0.

  • http://google.com Chad

    My success.php is all screwy. It can not seem to pick up the username from the DB. I get these errors:

    Notice: Undefined index: userName in J:\xampp\htdocs\WD260\finalproj\success.php on line 3

    Notice: Undefined variable: userName in J:\xampp\htdocs\WD260\finalproj\success.php on line 10

    Everything else seems to work great. any help?

    • praveen

      same here :(

      • http://www.computersneaker.com/ Mudasir Nazir

        Please Check Your code again, Or send me the error.

        • http://www.computersneaker.com/ Mudasir Malik

          use $_SESSION['userName']; instead of $userName;

  • praveen

    I cant see the user name after logging in.. there is an issue.. it shows an error Undefined index userName.. Do check it and serve soon..

    cheers.. Praveen

    • Dick King

      Hi, I have used this script and like Praveen I also cannot see the username on the successful page.

      I see the page and the Text but no user name.

      Can you help?

      Dick

      • http://www.computersneaker.com/ Mudasir Nazir

        I think you are not using sessions on your success page, Make sure that you have written session_start(); at the top of your success page. and then use username as $_SESSION['username'];
        I am sure that it will work.

        • ysf

          HI,im also still having problem displaying the username,i have tried everything but think im missing something,please explain further,thanks!

          <?php

          session_start();

          if($_SESSION['userName']!='')

          {

          header("location:login_form.php");

          }

          else

          {

          echo 'Successfully Login Welcome ‘.$userName.”;

          echo ‘ Log Out‘;

          }

          ?>

          • engrmudasirmalik

            this is like following
            Welcome

          • http://www.computersneaker.com/ Mudasir Malik

            use the followng code $_SESSION['userName']; instead of $userName;

  • http://www.damiengrass.com Damien

    No, It’s because you’ve done it wrong. Here’s what it should be:

    <?php
    session_start();
    if(isset($_SESSION['userName'])) {
    header("location:login_form.php");
    } else {
    echo 'Successfully Login Welcome ‘.htmlentities($_SESSION['userName'], ENT_QUOTES).”;

    echo ‘ Log Out‘;
    }

    ?>

    • Dick King

      Sorry guys, it’s still not working.

      Could it be that the login.php is not recording the session or passing it to the success.php?

      Dick

      • http://www.damiengrass.com Damien

        Yup.

        Under the “<?php" on login.php add "session_start();" (without the quotes).

        Use my success.php, too.

  • blabala

    how about if you’re going to put a re-type password?
    How would you do it?

  • Guest

    Notice: Undefined variable: userName in C:xampphtdocsblogin_success.php on line 11

    hi i am having an error like this i have session_start(); on my success login and login page but i am still having this error.

    this is the code i have

    <?php
    session_start();
    if(isset($_SESSION['userName'])!='')
    {
    header("location:login_form.php");
    }
    else
    {
    echo 'Successfully Login Welcome ‘.$userName.’ ‘;
    echo ‘ Log Out‘;
    }
    ?>

    its the same as your codes but there is still an error help me pls

  • xander

    Notice: Undefined variable: userName in C:xampphtdocsblogin_success.php on line 11

    hi i am having an error like this i have session_start(); on my success login and login page but i am still having this error.

    this is the code i have

    <?php

    session_start();

    if(isset($_SESSION['userName'])!='')

    {

    header("location:login_form.php");

    }

    else

    {

    echo 'Successfully Login Welcome ‘.$userName.’ ‘;

    echo ‘ Log Out‘;

    }

    ?>

    its the same as yours but i am still having an error help me please

    • http://www.computersneaker.com/ Mudasir Malik

      use the followng peice of code $_SESSION['userName']; instead of $userName;

  • http://www.facebook.com/robhit.saxena Robhit Saxena

    iam having this error after the successful login

    Data Does Not Match
    Re-Enter UserName and Password

    please help

    • http://www.computersneaker.com/ Mudasir Nazir

      Your session might not Working Properly. Check that you have used session_start();
      If it is so then your data does not match with your database records.

    • http://www.computersneaker.com/ Mudasir Malik

      Data does not match the required data, you need to enter this in right way. Enter the data that matches to login.

      • Dawood

        Assalam-o-Alikum.

        I am having the same message. I created the registration page and it showed everything successfully. But when I type my login information I get an error. Does the following script OK :-

  • adrian

    hi tnx for the codes but i have this error

    (Data Does Not Match &alt;br /> Re-Enter UserName and Password)

    • Usama Lucky

      yup i have the same error…….help us Bro….. :(

  • adrian

    hi again:))) fix already that first error but when i login there’s a error about this

    (
    Notice: Undefined index: $userName in C:xampphtdocssesuccess.php on line 3

    Notice: Undefined variable: userName in C:xampphtdocssesuccess.php on line 10)

    • http://www.computersneaker.com/ Mudasir Nazir

      hello Andrian
      If you want to use my code then please clear that bugs and then go with it.
      This variable might not been defined from you, that’s why its generating this error.

    • http://www.computersneaker.com/ Mudasir Malik

      use the followng peice of code $_SESSION['userName']; instead of $userName;

  • adrian

    tnx pls help

  • booruguru

    If you are looking for a no fuss login script that’s designed for newbies, try: http://userpie.com

  • Usama Lucky

    I am Having this error on success.php

    Warning: session_start() [function.session-start]: Cannot send session cookie – headers already sent by (output started at C:xampplitehtdocssuccess.php:4) in C:xampplitehtdocssuccess.php on line 5

    Warning: session_start() [function.session-start]: Cannot send session cache limiter – headers already sent (output started at C:xampplitehtdocssuccess.php:4) in C:xampplitehtdocssuccess.php on line 5

    Succefuly Login
    Welcom ‘..’

    Log Out

    Please Help me out bro…… :(

    • http://www.computersneaker.com/ Mudasir Malik

      Dear you need to use ob_start(); at the top of your code and use the following piece of code $_SESSION['userName']; instead of $userName;

  • alee

    im getting this error

    Notice: Undefined index: userName in C:xampphtdocslogsuccess.php on line 7

    Notice: Undefined index: userName in C:xampphtdocslogsuccess.php on line 14

    Successfully Login Welcome

    Log Out

    and my success.php code is..

    <?php

    session_start();

    ob_start();

    if($_SESSION['userName']!='')

    {

    header("location:login_form.php");

    }

    else

    {

    echo 'Successfully Login Welcome ‘.$_SESSION['userName'].”;

    echo ‘ Log Out‘;

    }

    ?>

    I also try your solution to do

    “Dear you need to use ob_start(); at the top of your code and use the following piece of code $_SESSION['userName']; instead of $userName;”

    but problem remain the same please tell me some other solution coz ur this solution dosent work…
    thnx