SnippetsProject Code

Simple User Login

Description

This little tutorial shows new users how to make a simple user login with a login form and database query.

Snippet

login_page.php

1
2
3
4
5
6
7
<form action="verify.php" method="post">
	User Name:<br>
	<input type="text" name="username"><br><br>
	Password:<br>
	<input type="password" name="password"><br><br>
	<input type="submit" name="submit" value="Login">
</form>

verify.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
<?php
if(isset($_POST['submit'])){
	$dbHost "localhost";		//Location Of Database usually its localhost
	$dbUser "xxxx";			//Database User Name
	$dbPass "xxxxxx";			//Database Password
	$dbDatabase "db_name";	//Database Name
	
	$db mysql_connect($dbHost,$dbUser,$dbPass)or die("Error connecting to database.");
	//Connect to the databasse
	mysql_select_db($dbDatabase$db)or die("Couldn't select the database.");
	//Selects the database
	
	/*
	The Above code can be in a different file, then you can place include'filename.php'; instead.
	*/
	
	//Lets search the databse for the user name and password
	//Choose some sort of password encryption, I choose sha256
	//Password function (Not In all versions of MySQL).
	$usr mysql_real_escape_string($_POST['username']);
	$pas hash('sha256'mysql_real_escape_string($_POST['password']));
	$sql mysql_query("SELECT * FROM users_table 
		WHERE username='$usr' AND
		password='$pas'
		LIMIT 1");
	if(mysql_num_rows($sql) == 1){
		$row mysql_fetch_array($sql);
		session_start();
		$_SESSION['username'] = $row['username'];
		$_SESSION['fname'] = $row['first_name'];
		$_SESSION['lname'] = $row['last_name'];
		$_SESSION['logged'] = TRUE;
		header("Location: users_page.php"); // Modify to go to the page you would like
		exit;
	}else{
		header("Location: login_page.php");
		exit;
	}
}else{	//If the form button wasn't submitted go to the index page, or login page
	header("Location: index.php");	
	exit;
}
?>

users_page.php

1
2
3
4
5
6
7
8
<?php
session_start();
if(!$_SESSION['logged']){
	header("Location: login_page.php");
	exit;
}
echo 'Welcome, '.$_SESSION['username'];
?> 

Comments

ADD YOUR COMMENT:

Formatting

Comments.
admin August 20th (Website)
To return to the index page after you login, you just need to modify the following 2 lines:

header(\"Location: login_page.php\");
exit;
admin August 20th (Website)
Thanks everyone for all your input! I have updated the snippet with everyones suggestions! If you have any more suggestions, please feel free to let me know! I am always listening.
Ebbsfleet July 17th (Website)
Is there a way of returning to the index after you login? its a great script as building the login needed exact function I have had problems at first but this is the best exp so far! thanks margret
Anonymous May 4th
Do not use this snippet, it is very poorly coded.
UK Software companies December 9th 2009 (Website)
Interesting,

Keep up the good work...

Thanks for bringing this up
CasTex November 23rd 2009 (Website)
Good work, I wish this has no vulnerabilities.
custom software November 4th 2009 (Website)
Its a great tutorial,

Its all fixed and working perfectly,

Keep up the good work,
Human_Bagel August 22nd 2008 (Website)
Yes, sir, there are huge SQL injection holes, and storing passes as plaintext is a BAD idea!

I agree with the previous poster, mysql_real_escape_strting() is the best way to prevent SQL injection.

Also, if using PHP5, I would strongly recommend using PHP's hash() function with SHA-512, Whirlpool, or Ripemd5-160. All of those hashes are 512 bits in length, compared to md5()s 40.

Correcting those two will fix the prominent security holes.

Cheers! Hope it helps!
Ryan August 21st 2008 (Website)
Updated!
Bond August 20th 2008
1. addslashes() is not sufficient enough to prevent SQL injection. Use mysql_real_escape_string().

2. You are not enclosing your values in quotes, this just means they need to have a space in their submission to inject SQL.

3. You should not ever echo out mysql_error() to an end user. Log it for your own purposes, but show the user a generic error message.

Your query would be better off like this:

<?php   
    $sql 
mysql_query("SELECT * FROM users_table 
    WHERE username='"
.mysql_real_escape_string($_POST['username'])."' AND
    password='"
.mysql_real_escape_string($_POST['password'])."' LIMIT 1")or die('Sorry, there has been a database error. The webmaster has been notified of the error. Please try again later.'); 
?>
Anonymous August 20th 2008
Oh a few more things, in regards to good coding:
The following have variables in quotes. You don't need the quotes, in fact it makes your script slow (albeit only slightly slower).

Also, again with my suggestion about error messages. Don't let the visitor know it couldn't connect to the database. They don't need to know this information. Log it for your own use (write to a file) and just tell them there is a problem with the website and to try again later.
<?php
$db 
mysql_connect("$dbHost","$dbUser","$dbPass")or die("Error connecting to database.");
    
//Connect to the databasse
    
mysql_select_db("$dbDatabase"$db)or die("Couldn't select the database.");
?>


Would be better off as:

<?php
    $db 
mysql_connect($dbHost,$dbUser,$dbPass)or die("The site is currently experiencing some problems. The issue will be dealt with shortly. Please try again at a later time.");
    
//Connect to the databasse
    
mysql_select_db($dbDatabase$db)or die("The site is currently experiencing some problems. The issue will be dealt with shortly. Please try again at a later time."); 
?>
Anonymous August 20th 2008
(That was me, the latest Anonymous poster)

One *last* thing. You're saving the passwords as plain text. BAD idea, especially with the SQL injection problems you have. Someone with the right knowledge can easily steal all your user's passwords.

I'd recommend using md5() to has the passwords (at very least md5, though sha1 would be nicer).

Try this:
<?php
$sql 
mysql_query("SELECT * FROM users_table
WHERE username='"
.mysql_real_escape_string($_POST['username'])."' AND
password=md5('"
.mysql_real_escape_string($_POST['password'])."') LIMIT 1")or die('Sorry, there has been a database error. The webmaster has been notified of the error. Please try again later.'); 
?>


And make sure you md5() the passwords when you insert them into the database initially.
gravlund May 8th 2007
Hi!

I'm getting this error message:
Unknown column 'Gravlund' in 'where clause'

what is wrong?
Admin March 26th 2007 (Website)
Are you placing any HTML or Text that will be sent to the source code in the verify.php page? If so, remove it, the user will never see this page.
Anonymous March 21st 2007
No i didn't...im that new.....am i suppose change them....im using ODBC
Newbie! March 21st 2007
I got pass that error now i gettin errors wit tha sessions
Warning: session_start() [function.session-start]: Cannot send session cookie - headers already sent by (output started at D:\websites\template_96\HTML\verify.php:9) in D:\websites\template_96\HTML\verify.php on line 38

Admin March 20th 2007 (Website)
Did you change these?<br />
<?php
$dbHost 
"localhost";        //Location Of Database usually its localhost<br />
$dbUser "xxxx";            //Database User Name<br />
$dbPass "xxxxxx";            //Database Password<br />
$dbDatabase "db_name";    //Database Name ?>
Newbiewebby March 12th 2007
When i run the login_page.php page it goes to the verify.php page and on that page i get Fatal error: Call to undefined function mysql_connect() in D:\websites\DE PHP\verify.php on line 16


Help Please
Newbie!
bob February 12th 2007
not putting an 'exit' after a header("Location: blahblah") request is not a wise move. headers used in this way are not honoured until the script has finished - so effectively, all code after it can still run
Admin February 12th 2007 (Website)
Fixed. Thank You.

Login



Did you want to add your own codes?
Create an Account its fast and easy!

Did you forget your username/password?
Have us reset it it for you!

Information

2.63 / 5 (308 votes)

12,570 views

11 downloads New

Code Tools

Bookmark and Share

Programmer

admin

Posted on: Jan 01, 2008

View all of Ryan's snips