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. February 2nd, 2009 at 20:41 | #1

    ‘$PHP_SELF’ to $_SERVER['PHP_SELF'] – And everything works fine, great tutorial!
    thanks a lot!

  2. February 3rd, 2009 at 16:44 | #2

    When Im logged in and Im try to login again I should get show_userbox(); – // The user is already loggedin, so we show the userbox. – but this don`t work for me :(
    Im getting this error:

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

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

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

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

  3. March 3rd, 2009 at 19:38 | #3

    It looks fine, but how do I protect pages, which should only be accesable by the members?
    Next to this: Once logged in, are you automaticall logged out when you leave the website?

  4. March 24th, 2009 at 13:33 | #4

    I also would like to know how to protect pages. Not sure on how I can redirect user to a page.

  5. March 24th, 2009 at 17:29 | #5

    whats a show_user box?

  6. March 25th, 2009 at 23:02 | #6

    @Omar
    whats a show_user box?
    in this case its just a logout link witch will be shown if a user logged in..
    I also would like to know how to protect pages.
    Simply check if the session variable exist:
    ie:
    session_start();
    if($_SESSION['loginid']){
    echo “user is allowed to view this”;
    } else {
    //else redirect him to an other side
    header(“Location: http://www.google.at“);
    }

    Once logged in, are you automaticall logged out when you leave the website?
    No, in fact it depend on your session life time… (take a look at php.ini)

    best regards nfo

  7. Lance
    April 22nd, 2009 at 11:01 | #7

    I noticed something in your login.php file that might cause issues down the line.
    In your SQL code where you query the database, you specify “LIMIT 1″, therefore only returning the first result. Further down, when you check whether the password matches, you also check whether the number of results is something other than 1. With “LIMIT 1″ in your SQL, this will always be 1.
    Personally, I would remove the “LIMIT 1″ from the SQL query, but leave the code that checks there is only 1 result.
    Otherwise, it is a great article.

  8. Fernando
    May 6th, 2009 at 03:12 | #8

    WOW.. FINALY! A script that works wonderfuly! I have been going nuts for days trying to find something that works!
    I do have one question though..
    I really want to take this script and make it so that depending on which user logs in, they go to a specific page.
    But I have NO clue how to go about doing this. Any help please would be very greatly appreciated!!!
    Many thanks once again!

  9. James
    May 23rd, 2009 at 01:28 | #9

    I encountered an annoying problem that continually resulted in me receiving a “wrong username or password” response even when the details where correct, (note: this is only when using the md5 version). If I used just plain text then everything would check-out fine.

    After a bit of reading over the code I decided to see what the ‘login.php’ was outputting as the md5 password. It turns out this was my problem, the md5-password outputted to the database is always 32 characters long irrespective of the form’s max-length password attribute. But I had my database password set to 25 characters max.

    Changing the mysql-database password field to 50 characters seemed to solve the problem, although 32 would probably have been enough.

    Another tip I came across was to set the password field (in the mysql database) to CHAR rather than VARCHAR and to BINARY. For example

    “CREATE TABLE ‘tblusers’ (‘username’ VARCHAR(30) NOT NULL, ‘password’ CHAR(40) BINARY NOT NULL);

    or

    “CREATE TABLE tblusers (username VARCHAR(30) NOT NULL, password CHAR(40) BINARY NOT NULL);

    depending on your version

  10. ANNI
    July 28th, 2009 at 12:06 | #10

    what is the use of function.inc.php file & index.php ?

  11. August 25th, 2009 at 13:18 | #11

    Hello work

    thanks

    but can i make it logon to my accounts table that i have

    soo i can make a voting page/donate

    5/5 rating

  12. wayne
    October 10th, 2009 at 13:32 | #12

    this works for me, protect other pages

  13. wayne
    October 10th, 2009 at 13:33 | #13
  14. wayne
    October 10th, 2009 at 13:34 | #14


  15. wayne
    October 10th, 2009 at 13:38 | #15

    soz not use to posting, i find this works for protecting other pages
    and i agree great script

  16. wayne
    October 10th, 2009 at 13:41 | #16

    nope cant seem to post php code for it
    how do i show you the code

  17. October 16th, 2009 at 10:14 | #17

    hello, i want to yous this code but i like to get after the login to a page in a private directory and al the pages have to be protected , how do i do this?

  18. Ravi
    November 7th, 2009 at 06:20 | #18

    This worked perfectly for me.. Thanks. Now I can work with my other features.

  19. Manish
    November 13th, 2009 at 20:37 | #19

    i successfully get this script in my index page but the problem is when i log in the form shows the error showing wrong username or password please help me

  20. December 13th, 2009 at 17:15 | #20

    For those of you trying to figure out how to do this, I used nfos code. Simply place this at the header of each page you with to protect:

  21. December 13th, 2009 at 17:50 | #21

    ?php
    // Start a session
    session_start();
    require_once (‘/secure/db_connect.inc.php’);
    require_once (“/secure/functions.inc.php”);
    ?>

  22. December 13th, 2009 at 17:51 | #22

    OK take 10, posted the wrong one:
    put at

  23. December 13th, 2009 at 17:52 | #23

    ?php
    // Start a session
    session_start();
    require_once (‘db_connect.inc.php’);
    require_once (“functions.inc.php”);
    if($_SESSION['loginid']){
    echo “”;
    } else {
    //else redirect to login page
    header(‘Location: /login.php’);
    }

  24. Brian
    January 20th, 2010 at 21:49 | #24

    Okay, I’m missing something.

    The script works fine with a simple index.php that simply calls the script. However, if I put the login script call at the top of a very busy index.php, it displays all of the index.php file with the login form on top.

    How can I keep the index.php data from displaying until someone has logged in?

    Thanks for all your efforts.

  25. pree
    February 3rd, 2010 at 08:48 | #25

    how will I made entry of login in time and date in another table for authenticated user? plz help me its urgent.

  26. February 19th, 2010 at 19:20 | #26

    Hello,

    Could someone email me how to change the activation link to my own site? Where do I put my website’s address and in what file?

    Thanks

Comment pages
1 2 10
  1. No trackbacks yet.