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:
- Creating the mysql table
- Creating a db_connect.inc.php file
- Creating the html login form
- Creating the login.php file
- Creating the logout.php file
- Creating a function.inc.php file
- 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> |
‘$PHP_SELF’ to $_SERVER['PHP_SELF'] - And everything works fine, great tutorial!
thanks a lot!
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!
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?
I also would like to know how to protect pages. Not sure on how I can redirect user to a page.
whats a show_user box?
@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
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.
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!
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