Home > PHP > Creating a simple login script with php and mysql

Creating a simple login script with php and mysql

Learn to create a simple login system with php and mysql in 7 simple steps:

Requirements:

  • Mysql database
  • a php & mysql enabled host
  • ftp access to your website

Overview

Steps:

  1. Creating the mysql table
  2. Creating a db_connect.inc.php file
  3. Creating the html login form
  4. Creating the login.php file
  5. Creating the logout.php file
  6. Creating a function.inc.php file
  7. Adding the script to index.php

Step 1: Creating the mysql table

For this tutorials i presume you already know how to add tables to your database.

Table login (SQL code):

1
2
3
4
5
6
7
CREATE TABLE `login` (
  `loginid` INTEGER UNSIGNED NOT NULL AUTO_INCREMENT,
  `username` VARCHAR(50) NOT NULL,
  `password` VARCHAR(45) NOT NULL,
  `email` VARCHAR(255) NOT NULL,
  PRIMARY KEY (`loginid`)
);

Now let us add the administrator account:

  • username: admin
  • password: yourpasswordhere

** Change the text yourpassword here with the desired password.
** Change the text youremailhere with your email adress.

SQL query:

1
insert into login (username,password,email) value ('admin',md5('yourpasswordhere'),'youremailhere');

The table is now ready, and the administrator account has been added. let us move on to step 2.

Step 2: Creating a db_connect.inc.php file

This file will be used to manage the connection to the database.

File db_connect.inc.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
<?php
// Database settings
// database hostname or IP. default:localhost
// localhost will be correct for 99% of times
define("HOST", "localhost");
// Database user
define("DBUSER", "dbusername");
// Database password
define("PASS", "dbpassword");
// Database name
define("DB", "dbname");
 
############## Make the mysql connection ###########
$conn = mysql_connect(HOST, DBUSER, PASS);
if (!$conn)
{
    // the connection failed so quit the script
    die('Could not connect !<br />Please contact the site\'s administrator.');
}
$db = mysql_select_db(DB);
if (!$db)
{
    // cannot connect to the database so quit the script
    die('Could not connect to database !<br />Please contact the site\'s administrator.');
}
?>

Let me explain:

  • HOST: this is the location for the database server it can be a hostname or an ip adress. it is usualy localhost.
  • DBUSER: this is the database user account used to access the database.
  • PASS: this is the password for the database user account.
  • DB: this is the name of the database used.

Step 3: Creating a login form

File loginform.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
<form name="login-form" id="login-form" method="post" action="<?php echo $PHP_SELF; ?>"> 
  <fieldset> 
  <legend>Please login:</legend> 
  <dl> 
    <dt> 
      <label title="Username">Username:
      <input tabindex="1" accesskey="u" name="username" type="text" maxlength="50" id="username" /> 
      </label> 
    </dt> 
  </dl> 
  <dl> 
    <dt> 
      <label title="Password">Password:
      <input tabindex="2" accesskey="p" name="password" type="password" maxlength="15" id="password" /> 
      </label> 
    </dt> 
  </dl> 
  <dl> 
    <dt> 
      <label title="Submit"> 
      <input tabindex="3" accesskey="l" type="submit" name="cmdlogin" value="Login" /> 
      </label> 
    </dt> 
  </dl> 
  </fieldset> 
</form>

Step 4: Creating the login.php file

In this step we will make the actual login check, first well check if the user is already logged in and if so we will show the correct information.
If the user is not checked in we will print the login form on the page, once the user has pressed the login button, we will check his username and password.
If his username and password are correct we will save his login ID for later use and also his username.

File 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
43
44
45
46
<?php
if (!session_is_registered('loginid') || !session_is_registered('username'))
{
	// user is not logged in.
    if (isset($_POST['cmdlogin']))
    {
        // retrieve the username and password sent from login form
        // First we remove all HTML-tags and PHP-tags, then we create a md5-hash
        // This step will make sure the script is not vurnable to sql injections.
        $u = strip_tags($_POST['username']);
        $p = md5(strip_tags($_POST['password']));
        //Now let us look for the user in the database.
        $query = sprintf("SELECT loginid FROM login WHERE username = '%s' AND password = '%s' LIMIT 1;",
            mysql_real_escape_string($u), mysql_real_escape_string($p));
        $result = mysql_query($query);
        // If the database returns a 0 as result we know the login information is incorrect.
        // If the database returns a 1 as result we know  the login was correct and we proceed.
        // If the database returns a result > 1 there are multple users
        // with the same username and password, so the login will fail.
        if (mysql_num_rows($result) != 1)
        {
            // invalid login information
            echo "Wrong username or password!";
            //show the loginform again.
            include "loginform.php";
        } else {
            // Login was successfull
            $row = mysql_fetch_array($result);
            // Save the user ID for use later
            $_SESSION['loginid'] = $row['loginid'];
              // Save the username for use later
            $_SESSION['username'] = $u;
              // Now we show the userbox
            show_userbox();
        }
    } else {
    	 // User is not logged in and has not pressed the login button
    	 // so we show him the loginform
        include "loginform.php";
    }
 
} else {
	 // The user is already loggedin, so we show the userbox.
    show_userbox();
}
?>

Step 5: Creating the logout.php file

The logout file will destroy the session and it’s stored information. Afterwards it will redirect the user to the homepage.

File logout.php:

1
2
3
4
5
6
7
8
9
10
11
12
13
<?php 
session_start();
if( session_unregister('loginid') == true 
		&& session_unregister('username')==true ) {
   header('Location: index.php');
   session_destroy();
} else {
   unset($_SESSION['loginid']);
   unset($_SESSION['username']);
   session_destroy();
   header('Location: index.php');
}
?>

Step 6: Creating a function.inc.php file

Now we will create a file that will store all our functions, by including this file all our functions will be accessable.
It will help keep track of your functions and will make it harder to abuse any of them.

File functions.inc.php:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<?php
 
function show_userbox()
{
    // retrieve the session information
    $u = $_SESSION['username'];
    $uid = $_SESSION['loginid'];
    // display the user box
    echo "<div id='userbox'>
	 Welcome $u
		<ul>
		   <li><a href='./logout.php'>Logout</a></li>
		</ul>
             </div>";
 
}
?>

Step 7: Adding the script to index.php

This is probably the most easy step of em all.
All we need to do is include some files in the index.php file and voila!

File index.php:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<?php 
// Start a session
session_start();
require_once ('db_connect.inc.php');
require_once ("functions.inc.php");
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Simple Login tutorial</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
</head>
<body>
<?php
include "login.php";
?>
</body>
</html>

Categories: PHP Tags: , , , , , ,
  1. Adam
    December 23rd, 2007 at 05:56 | #1

    There is an error, Undefined variable: PHP_SELF in C:\www\vhosts\localhost\rcms\loginform.php on line 1

    How do I correct this? You have $PHP_SELF as the form action. But it doesn’t work. I copied it exactly as its shown in the examples above. I know its not $_SERVER['php_self'] as that produced the same result.

  2. December 23rd, 2007 at 22:38 | #2

    I’ve also encounterd this problem with some server setup’s. But there’s a quick workaround to solve this problem:

    Change the this line:

    [cc lang='html']

    [/cc]

    This should fix the problem.

    **Note the form action should be linked to the correct adress, by default the loginscript is included into the index.php file. this is where the form should point to, if for example the login was included into a file called hello.php the form action would be ‘hello.php’.

    I hope this solved your problem.

  3. Adam
    December 24th, 2007 at 21:25 | #3

    Thanks, it worked. Would you say this is secure?

  4. December 25th, 2007 at 13:35 | #4

    The tutorial was created in order to give you a basic understanding of how to create a loginscript. It itself was not build as to be the most secure script out there but,
    I would say this is reasonably secure, but i would not call it airthight tho.

    If airtight security is a must you can check out:
    http://phpsec.org/projects/guide/

    This is a complete guide into PHP security.

    When i find the time i will create a new login tutorial that has airtight security in mind.
    Greetings

  5. john
    January 3rd, 2008 at 00:49 | #5

    but how do you allow a user to register and use this script properly?

  6. elicia
    January 3rd, 2008 at 07:51 | #6

    Thanks, this code help me a lot thanks again

  7. January 3rd, 2008 at 15:40 | #7

    @ john

    Those actions were not in the scope of the tutorial itself, i’m currently working on a new tutorial that implents both a secure login and register/lost password actions.

    Be sure to check back in a couple of days.

  8. January 6th, 2008 at 18:34 | #8

    Great tutorial! I’ll be implementing this to my site soon!!

  9. January 6th, 2008 at 19:28 | #9

    Brilliant! Works like a charm, thanks for this and keep up the great tutorials!

  10. January 7th, 2008 at 22:37 | #10

    I’m still waiting for the “Registration and Confirmation Email”
    I could really use that now that I have this ;-P

    Your awesome!

    ~Ryan

  11. Amy
    January 14th, 2008 at 23:24 | #11

    Warning: mysql_connect() [function.mysql-connect]: Access denied for user ‘dbusername’@'localhost’ (using password: YES) in F:\wamp\www\GAME\db_connect.inc.php on line 14
    Could not connect !
    Please contact the site’s administrator.

  12. January 14th, 2008 at 23:25 | #12

    Excellent post!

  13. Sliphead
    January 15th, 2008 at 19:52 | #13

    It could be useful to change ‘$PHP_SELF’ to $_SERVER['PHP_SELF'] or $_SERVER['REQUEST_URI'], because registered globals could be default off in the php.ini, it’s even better to use request_uri, so that the action will happen eg at index.php?page=contact, and not only index.php.

    Nice tutorial,

    Sliphead

  14. January 17th, 2008 at 23:13 | #14

    I tried to remove something now, then it came;

    Warning: mysql_real_escape_string() [function.mysql-real-escape-string]: Access denied for user ‘ODBC’@'localhost’ (using password: NO) in C:\Programfiler\wamp\www\login.php on line 14

    Warning: mysql_real_escape_string() [function.mysql-real-escape-string]: A link to the server could not be established in C:\Programfiler\wamp\www\login.php on line 14

    Warning: mysql_real_escape_string() [function.mysql-real-escape-string]: Access denied for user ‘ODBC’@'localhost’ (using password: NO) in C:\Programfiler\wamp\www\login.php on line 14

    Warning: mysql_real_escape_string() [function.mysql-real-escape-string]: A link to the server could not be established in C:\Programfiler\wamp\www\login.php on line 14

    Warning: mysql_query() [function.mysql-query]: Access denied for user ‘ODBC’@'localhost’ (using password: NO) in C:\Programfiler\wamp\www\login.php on line 15

    Warning: mysql_query() [function.mysql-query]: A link to the server could not be established in C:\Programfiler\wamp\www\login.php on line 15

    Warning: mysql_num_rows(): supplied argument is not a valid MySQL result resource in C:\Programfiler\wamp\www\login.php on line 18
    Wrong username or password!

  15. January 17th, 2008 at 23:53 | #15

    Thanks alot, i fixed it now :D it works^^

  16. January 23rd, 2008 at 15:23 | #16

    Is there a simple way of changing it so theres a remeber me checkbox and if checked it will create cookies that remember login details. Been trying to get it working but can’t.

  17. mike
    January 24th, 2008 at 09:45 | #17

    Warning: mysql_real_escape_string() [function.mysql-real-escape-string]: Access denied for user ‘ODBC’@’localhost’ (using password: NO) in C:\Programfiler\wamp\www\login.php on line 14

    please elp me with this stuff

  18. Darius
    January 25th, 2008 at 10:24 | #18

    How I can check from another page that user already logged in ?
    I trying:

    but nothing…

  19. Darius
    January 26th, 2008 at 10:32 | #19

    mike,
    try to check your “connector” to db. (db_connect.inc.php)

  20. January 30th, 2008 at 01:01 | #20

    Ok i have copied everything as stated however i’m getting an error:

    Warning: mysql_connect() [function.mysql-connect]: Can’t connect to MySQL server on ‘localhost’ (10061) in d:\hshome\watsonowen\watsonowen.com\db_connect.inc.php on line 14
    Could not connect !
    Please contact the site’s administrator.

    I have checked that my MySQL datebase is set to localhost, I have put the user and
    password into it along with the DB that i wanted however it’s still giving me this error.
    Anyone help?

  21. January 30th, 2008 at 11:58 | #21

    @ darius

    every page that’s not included in the index.php page:

    [cc lang='php']
    < ?php
    session_start(); // this has to be on the very first line of the page!

    if (session_is_registered('loginid') || session_is_registered('username'))
    {
    //user is logged in
    }

    ?>[/cc]

    @ mike

    it seems your using the wrong username / password combination, please use the username and password used to connect to your database server, if your using a hosting it should be created in the admin panel or you should have recieved this information.

    @ owen watson

    Please make sure the supplied database name exists on the database server, if it does not exist the script cannot connect to it, also, use the advice from mike aswell. If that still does not seem to work, please check to see if your database is running the correct port (default 3360).

    Hope that fixes it?

  22. February 5th, 2008 at 02:16 | #22

    Thank you for setting this up Its been a great help… but I’ve temporaraly had to move the Index and i’m rather confused about the connector… I’m getting the same error as mike but i don’t know what or how to change it

  23. February 5th, 2008 at 03:24 | #23

    was playing with the script a bit now the error has changed to:
    Could not connect !
    Please contact the site’s administrator.

  24. February 5th, 2008 at 03:41 | #24

    NVM i got it now

  25. Omid
    February 5th, 2008 at 21:47 | #25

    It works for me but there is one problem , two user with same user and pass can login in same time :(
    How could I correct it ?

  26. February 5th, 2008 at 23:34 | #26

    @omid: This tutorial was ment to be a starting point, it should not be used as the login script of an actual live site.

    A better one for using on your live site is:
    http://www.ineedtutorials.com/articles/complete-advanced-login-member-system-php-tutorial

    it also fixed your problem with double login (this one was not broken, it simply did not check to see if there were double usernames.)

    hope it help greets

  27. February 25th, 2008 at 07:30 | #27

    how to use include function for calling into a particular line of that included file in php

    my login.php contains

    $query = “SELECT id FROM new_user WHERE user_id=’”.$_POST['userid'].”‘ AND password=’”.$_POST['passwd'].”‘ “;
    $result = mysql_query($query);
    $num = mysql_num_rows($result);

    if($num>0){

    include “loginform.php”;
    echo ” Successfully,Logged in
    Log OUT
    Click here if your browser is not redirecting automatically or you don’t want to wait.“;

    }
    else {
    session_unset();

    include “loginform.php”;
    echo “Wrong Login. Use your correct Userid and Password and Try
    “;

    }

    if i want to redirect that perticular result of num function in loginform.php file what code i ahve to put in loginform.php

  28. Maurice
    March 7th, 2008 at 22:53 | #28

    Having multiple users with the same username is a weird design i think, but your check for multiple users with the same username/password is crippled by having the LIMIT 1 in the SQL query. This wil never return more then one row.

  29. March 29th, 2008 at 07:44 | #29

    hi,
    i try execute this below programme and also i create the database but it
    not work.

    i try to excute this on to Wamp but it gives me an error.

    ***Warning: mysql_connect() [function.mysql-connect]: Access denied for user ‘md5′@’localhost’ (using password: YES) in C:\wamp\www\db_connect.inc.php on line 14
    Could not connect !
    Please contact the site’s administrator.***

    please help me
    nikee

  30. GURU_al
    April 8th, 2008 at 01:34 | #30

    i keep getting a wrong username and password error…any suggestions…

  31. GURU_al
    April 8th, 2008 at 01:35 | #31

    repost

    I keep getting a wrong username and password when trying to login…any suggestions??

  32. April 9th, 2008 at 05:35 | #32

    Hi,

    This tutorial really works.

    I like this.

    Thanks

  33. May 4th, 2008 at 12:00 | #33

    Hi ,

    Excellent tutorial !! i have been tearing my hair out trying to locate a login script which is simple to understand and deploy. Found one here !!!
    For the past 3 days (and 2 nights) i have been trawling the web and dreaming in code attempting to resolve an apparently simple issue .You have aced it !
    Many thanks !!!

    anjanesh

  34. May 4th, 2008 at 12:04 | #34

    Guru @ 33
    i got the same error – resolved !
    the script looks up md5 values in the mysql table.You would need to store the md5 values in the table or if you would like to store/retrieve plain text passwords(= not a good idea) try this
    original code
    $p = md5(strip_tags($_POST['password']));
    replaced with
    $p = strip_tags($_POST['password']);
    this means you can now call plain text passwords.

    php database wizard – a free ware found at
    http://dbwizard.pages4u.net/news.php
    is a absolute necessity for trouble free database manipulation !!!
    i believe.

  35. May 11th, 2008 at 19:33 | #35

    I like this script! I’m only recive a warning after logging in:

    Warning: mysql_num_rows(): supplied argument is not a valid MySQL result resource in J:\XAMPP\htdocs\websites\SvenCoppers.be\login\login.php on line 20

    also the userbox isn’t visible

  36. June 5th, 2008 at 07:32 | #36

    I’m getting an error : Parse error: syntax error, unexpected ‘<’ in /customers/test-dig.dk/test-dig.dk/httpd.www/log/loginform.php on line 2

    I hope that some one can fix the problem..

    the php code
    [PHP]
    <?php

    Please login:

    Username:

    Password:

    ?>

    [/PHP]

  37. June 5th, 2008 at 07:34 | #37

    This website will not post the php code but here it is again.

    <?php

    Please login:

    Username:

    Password:

    ?>

  38. June 6th, 2008 at 09:05 | #38

    sorry but i am not able to few your coding properly the page is too small and some words are incomplete or deleted

  39. June 8th, 2008 at 20:08 | #39

    This works brilliantly

  40. June 8th, 2008 at 20:10 | #40

    IB

    The problem I think you are having is because in PHP you cannot just
    type text like you can in HTML Iv only just started learning but

    you would have to have it like

  41. Bubu
    June 12th, 2008 at 05:55 | #41

    I am getting an error on my logout page: “Warning: session_start(): Cannot send session cache limiter – headers already sent (output started at /home/www/nuflexfitness.com/logout.php:1) in /home/www/nuflexfitness.com/logout.php on line 2

    Warning: Cannot modify header information – headers already sent by (output started at /home/www/nuflexfitness.com/logout.php:1) in /home/www/nuflexfitness.com/logout.php on line 5″

    Any suggestions???

  42. June 14th, 2008 at 11:42 | #42

    Excellent tutorials.Keep it up

  43. June 22nd, 2008 at 01:46 | #43

    I keep getting this:

    Warning: session_start() [function.session-start]: Cannot send session cookie – headers already sent by (output started at /home/content/s/b/d/sbdun7/html/index.php:1) in /home/content/s/b/d/sbdun7/html/index.php on line 3

    Warning: session_start() [function.session-start]: Cannot send session cache limiter – headers already sent (output started at /home/content/s/b/d/sbdun7/html/index.php:1) in /home/content/s/b/d/sbdun7/html/index.php on line 3

    Any help with is would be great.
    Thanks

  44. Maani
    July 9th, 2008 at 09:22 | #44

    Very nice tutorial but i am waiting for registration form tutorial which i wish very simple similar to this

  45. MR.Sangi
    July 14th, 2008 at 06:44 | #45

    See, What happened?
    Now I am going to check the code then discuss later.

  46. shelltox
    September 18th, 2008 at 12:22 | #46

    thanks it works perfect

  47. Ian
    October 3rd, 2008 at 09:32 | #47

    The file /F:/Web 2008/Suppleform/test/ cannot be found?????????????

    Why is this?

  48. November 15th, 2008 at 17:46 | #48

    Great tutorial….

  49. rubax
    December 10th, 2008 at 22:10 | #49

    i keep having a problem
    i have multiple pages i want to secure and i link to them on function.inc.php
    when i’ not logged in and i go with an url to such a page i can see that page how can i solv this problem?

  50. gobi
    January 18th, 2009 at 22:42 | #50

    excelent login script.thanx a lot.

Comment pages
1 2 10
  1. No trackbacks yet.
Data Recovery Software