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):
`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:
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:
// 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:
<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:
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:
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:
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:
// 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>
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.
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:
into:
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.
Thanks, it worked. Would you say this is secure?
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
but how do you allow a user to register and use this script properly?
Thanks, this code help me a lot thanks again
@ 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.
Excellent post. thanks so much.
http://www.golfnorwich.com/
Great tutorial! I’ll be implementing this to my site soon!!
Brilliant! Works like a charm, thanks for this and keep up the great tutorials!
I’m still waiting for the “Registration and Confirmation Email”
I could really use that now that I have this ;-P
Your awesome!
~Ryan
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.
Excellent post!
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
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!
Thanks alot, i fixed it now
it works^^
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.
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
How I can check from another page that user already logged in ?
I trying:
but nothing…
mike,
try to check your “connector” to db. (db_connect.inc.php)
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?
@ darius
every page that’s not included in the index.php page:
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
}
?>
@ 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?
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
was playing with the script a bit now the error has changed to:
Could not connect !
Please contact the site’s administrator.
NVM i got it now
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 ?
@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
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
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.
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
great post and comments.
Thanks for sharing.
http://www.floors4u.net/
i keep getting a wrong username and password error…any suggestions…
repost
I keep getting a wrong username and password when trying to login…any suggestions??
Hi,
This tutorial really works.
I like this.
Thanks
I have it on my site: www.myfunbay.com/index.php
but the only thing i get is a blanck screen
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
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.
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
kRJLtK jr39ug7djalfgpitg94gbvm
?
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]
This website will not post the php code but here it is again.
<?php
Please login:
Username:
Password:
?>
sorry but i am not able to few your coding properly the page is too small and some words are incomplete or deleted
This works brilliantly
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
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???
Excellent tutorials.Keep it up
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
Very nice tutorial but i am waiting for registration form tutorial which i wish very simple similar to this
See, What happened?
Now I am going to check the code then discuss later.
Add A Comment