Very Basic User Login Using Cookies and MySQL

Here is a single script for user authentication checking. With this script you will only need this page to authenticate users for your “members only sections” Most utilities like this like to use three pages. One for the username password form one for the authentication and one for the successful login page. If found that bulky so I whittled it down to one script.

I have not tested this script against a database let me know if you find an error with the script and I will make corrections.

[php]<?php
session_start();
ob_start();

function login () {
?>

Please login.














Username:
Password:

<?php } if ($_COOKIE["auth"] == "1") { // Checks Session for an authorized cookie. ###################################################################################### # This is where you redirect or do other things for successful cookie authorization # ###################################################################################### echo "User Already Authenticated For This Session."; /************************************************************************************* This code is used at the top of pages that you would like to require user authentication on or "members only pages" session_start(); if ($_COOKIE["auth"] == "1") { $display_block = "

You are an authorized user.

"; } else { //redirect back to login form if not authorized header("Location: authenticate.php"); exit; } *************************************************************************************/ } else { if (!$_POST) { // Checks for empty forms on submission login (); } else { $username = $_POST['userLogin']; //sets post information to variables $password = $_POST['userPassword']; //sets post information to variables //connect to server and select database $mysqli = mysqli_connect("localhost", "joeuser", "somepass", "database"); //create and issue the query $sql = "SELECT * FROM auth_users WHERE username = '".$username."' AND password = PASSWORD('".$password."')"; $result = mysqli_query($mysqli, $sql) or die(mysqli_error($mysqli)); //get the number of rows in the result set; should be 1 if a match if (mysqli_num_rows($result) == 1) { setcookie("auth", "1", 0, "/", "yourdomain.com", 0); header("Location: authenticate.php"); } else { ?>
		<h2>The username and/or password you entered were incorrect.</h2>
<?php login (); } } } ?>[/php]

What’s stopping me from changing my auth level with the cookie?
You need to move away from cookies and use database authentication with sessions.

Notice how it says “Very Basic” in the subject line. Also Notice that there is only one “Auth Level” and thats authorized or not authorized. This is not meant to secure national secrets it is meant to keep people out of a single area. I understand that there are better ways to authenticate users. However, this is a valid method and it works. If you feel that it is not secure enough then feel free to write your own tutorial.

Hey Andrew,

First off, thank you for the very basic tutorial, I feel like I have been patchworking together different things that I have learned, and I now feel a little more confident seeing a finished version (how it should be written). The only thing that I would ask for is a breakdown of how each thing works, I am still getting a handle on things, so it’s all a little overwhelming to be honest.

Once again, thank you for taking the time to do this, it is a HUGE help!

Also, the passwords in the database are md5 hashed, I am looking for a place within the code you displayed, but I am missing something.

Thanks again!

If it helps, in the past I have put it on a line like this one:
[php]$mypassword = md5 mysql_real_escape_string($mypassword);[/php]

I’ll answer your last questions first, My code uses the MySQL PASSWORD function to hash the passwords in the database when the rows are created. So, when I query the database I need to use that function to check the hashes. If you are not using the MySQL PASSWORD function you should check the value as a string just like the username value. The method I am using allows me to enter passwords for this auth table manually, the hash is automatically created for me.

If I can I will edit my original post and add comments.

I think my main problem is I am piggy backing off of a database that was created using SugarCRM. I was using the users table in that database for the usernames and passwords to make it easier on myself since I already connect to it in my script to search the documents table.

Here is the code with more comments.

[php]<?php
// session_start() creates a session or resumes the current one based on a session identifier passed via a GET or POST request, or passed via a cookie.
session_start();

// This function will turn output buffering on. While output buffering is active no output is sent from the script (other than headers), instead the output is stored in an internal buffer.
ob_start();

// create a function to call the login form so you don’t have to duplicate code elsewhere. This could be done in another file.
function login () {
?>

	<h2  align="center">Please login.</h2>
		<form method="post" action="authenticate.php">
			<table  align="center">
				<tr>
					<td>Username:</td>
					<td><input type="text" name="userLogin" /></td>
				</tr>
				<tr>
					<td>Password:</td><td>
                                    <!-- The input type password is used to hide the text typed with *** or dots -->
					<input type="password" name="userPassword" /></td>
				</tr>
				<tr>
					<td colspan="2" align="center"><input type="submit" name="submit" value="Submit" /></td>
				</tr>
				</table>
		</form>
<?php } // Checks Session for an authorized cookie. if ($_COOKIE["auth"] == "1") { ###################################################################################### # This is where you redirect or do other things for successful cookie authorization # ###################################################################################### echo "User Already Authenticated For This Session."; /************************************************************************************* This code is used at the top of pages that you would like to require user authentication on or "members only pages" session_start(); if ($_COOKIE["auth"] == "1") { $display_block = "

You are an authorized user.

"; } else { //redirect back to login form if not authorized header("Location: authenticate.php"); exit; } *************************************************************************************/ } else { // Checks for empty forms on submission if it is empty it calls the login function if (!$_POST) { login (); } else { // sets the variables from the login form to php variables. $username = $_POST['userLogin']; //sets post information to variables $password = $_POST['userPassword']; //sets post information to variables //connect to server and select database $mysqli = mysqli_connect("localhost", "joeuser", "somepass", "database"); //create and issue the query // this query assumes your using MySQLs password function to hash your passwords if you are not using MySQLs PASSWORD function you need to change the query to SELECT * FROM auth_users WHERE username = '".$username."' AND password = '".$password."' this query checks the password as a string value. $sql = "SELECT * FROM auth_users WHERE username = '".$username."' AND password = PASSWORD('".$password."')"; // this line actually executes the query if there is an error it will output the error. $result = mysqli_query($mysqli, $sql) or die(mysqli_error($mysqli)); //get the number of rows in the result set; should be 1 if a match // this line simply checks to see if you returned one row from the query with a successful query (username & password match) you should only get one result. It could be possible for more than one row to have the same username and password but that is a duplication and database error. if (mysqli_num_rows($result) == 1) { //This line actually sets the cookie for your authentication using the cookie name auth and your domain name setcookie("auth", "1", 0, "/", "yourdomain.com", 0); //This line redirects your user after authentication to another page. in this case it redirects them back to this page and you should get the conformation message from above that they are already authorized. header("Location: authenticate.php"); } else { // this is what happens if you do not get one row from the mysql query. ?>
		<h2>The username and/or password you entered were incorrect.</h2>
<?php login (); } } } ?>[/php]

I hope you find this documentation more helpful.

Above and beyond what I had hoped for, you sir are a saint!

My guess is that the SugarCRM is using something more than just an md5 hash for their passwords. You should check their formula and try and recreate that for checking passwords. If it is md5 then your lucky if it is not well post it and we can help.

Luckily, I was able to grab the hash value straight from the database and run it through a decryptor and I got the correct results. Looks like I need to install the mysqli extension to make some of this code work, I will check back with you when I am done with that.

You should be able to substitute the mysql extension. You will just have to make the proper additions for database selection.

When I do the substitution, I get this error:

Warning: mysql_query(): supplied argument is not a valid MySQL-Link resource in /test/authenticate.php on line 75

Which is this line:
[php] $result = mysql_query($mysql, $sql) or die(mysql_error($mysql));[/php]

I can’t really tell if this looks correct, in the script I learned previously, I used this:

[php]$result=mysql_query($sql);[/php]

When your using mysql_query you do not need to connector information/variable in the query. With mysqli you do. Your second script should work but add the die line.

OK, so everything seems correct, except it is telling me No database selected after I enter my credentials. Any thoughts?

Check this out should help.
http://php.net/manual/en/function.mysql-select-db.php

Thanks, I will run through that over the weekend and see what I can come up with!

Sponsor our Newsletter | Privacy Policy | Terms of Service