Login forms and cookies with php

Click Here! to Download 10,000 Fonts
I recently posted a hacker challenge that consisted in a vulnerable login form, and specifically the vulnerabilities was found in the way the cookie was set, well for this tutorial I’ve decided to do a basic introduction to the mechanics of login forms and cookies in php using mysql as the database backend. On the application side, you can use cookies in you PHP scripts to control access to certain areas of your web site. A cookie is a small amount of data stored by the user’s browser in compliance with a request from a server or script. A host can request that up to 20 cookies be stored by a user’s browser.

Each cookie consist of a name, value, and expiry date. An individual cookie is limited to 4kb. After a cookie is set, only the originating host can read the data, ensuring that the user’s privacy is respected. Furthermore, the user can configure her browser to notify him of all cookies set, or even to refuse all cookie request. For this reason, cookies should be used in moderation and should not be relied on as an essential element of an environment.

The Anatomy of a Cookie.

A PHP script that sets a cookie might send headers that look something like this:

As you can see this Set-Cookie header contains a name/value pair. The name and value will be URL encoded. Should it be present, an expires field is an instruction to the browser to “forget” the cookie after given time and date.  if the browser is configure to store cookies, it will then keep this information until the expiry date. If the user points the browser at any page that matches the path and domain of the cookie, it will resend the cookie to the server. The browser’s headers might look something like this:

A PHP script will then have access to the cookie in the environment variable HTTP_COOKIE or as part of the $_COOKIE superglobal

print “$_SERVER[HTTP_COOKIE]<br>”;     // prints “site_user=22af645d1859cb5ca6da0c484f1f37ea”

print $_COOKIE[‘site_user’].”<br>”;        //prints “22af645d1859cb5ca6da0c484f1f37ea”

Setting a Cookie with PHP.

To set the cookie in PHP we will be using the function setcookie() which does just that, it outputs a Set-Cookie header. For that reason, it should be called before any other content is sent to the browser. The function accepts the cookie name, cookie value, expiry date.

The following script uses the setcookie() function to set the cookie.
setcookie(“site_user”, “username”, time()+3600, “/”);
if (isset($_COOKIE[‘site_user’])) {
print “<p>Hello $_COOKIE[site_user]</p>”;
} else {
print “<p>Hello, This is your first visit</p>”;

Even though we set the cookie in line 2 when the script is run for the first time, the $_COOKIE[‘site_user’] variable will not be created at this point. A cookie is read only when the browser sends it to the server. This will not happen until the user revisits the page. We set the cookie in your domain. We set the cookie name to “site_user” on line 2 and the cookie value to “username”, although this is just a simple intro to setting cookies with php note that setting the value of the cookie to a clear text presents a security risk for your application. We set the time() function to get the current time stamp and add 3600 to it (there are 3600 seconds in an hour). This total represents our expiry date. We define a path of “/”, which means that a cookie should be sent page within our server environment.

Deleting the Cookie.

Officially, to delete a cookie, you should call setcookie() with the name argument only:
setcookie( “site_user”);

This approach does not always work well, and should not be relied on. It is safest to set the cookie with a date that has already expired:

setcookie(“site_user”, ” “, time()-60, “/”);

You should also ensure that you pass setcookie() the same path domain, and secure parameters as you did when originally setting the cookie.

Restricting Access Based on Cookie Values:

Ok, now it starts to get more interesting…using your cookie skills to restrict access to parts of your web site. Suppose you created a login form that checked for values against a database. If the user is authorized, you send a cookie that says as so. then  for all pages you want to restrict only to authorized users you check for the specific cookie. if the cookie is present the user can see the page. If the cookie is not present, the user is either sent back to the login form, or a message regarding access restriction can be printed to the screen.

We’ll go through each step in the next section.

Creating the Authorized Users Table.
When you’re integrating user accounts into a Web-based application, it is most common to store the user specific information in a database table. The information in this table can then be queried to authorize the user and grant access to areas of the site that are specifically for these “special” users.

first lets create the table in our mysql database, this table will hold our username and passwods, the table is called auth_users, with fields for “id”, “first name”, “last name”, “email”, “username”, “password”.

CREATE TABLE auth_users (
id int not null primary key auto_increment,
f_name varchar(50),
l_name varchar(50),
email varcahr(150),
username varchar(25),
password varchar(75)

The following insert command puts a record in the auth_users table for a user named John Doe, with an email address of john@doe.com a username of jdoe and a password of doepass:

mysql> INSERT INTO auth_users value (1, ‘John’, ‘Doe’, ‘john@doe.com’, ‘jdoe’, password(‘doepass’));

This insert command is pretty simple with the exception of the use of password() function. When this function is used in the insert command, what is stored in the table is in fact not the actual password, but a hash of the password.

when you view the content of the auth_users table, you will see the hash in the password field.

mysql> SELECT * FROM auth_users;

creating the login form and script.

After you authorize users in your table you need to give them a mechanism for proving their authenticity. In this case a simple two field form will do as shown in the next script

<title>Login Form</title>
<H1>Login Form</H1>
<FORM METHOD=”POST” ACTION=”checklogin.php”>
<INPUT TYPE=”text” NAME=”username”></p>
<INPUT TYPE=”password” NAME=”password”></p>
<P><INPUT TYPE=”SUBMIT” NAME=”submit” VALUE=”Login”></P>

put this script into a text file called login.php, and here’s how the login page is suppose to look…

Next we will be creating the actual script that would be doing all the authentication and setting the cookie, name the following script checklogin.php, put both of this script in the root folder of your web server document root

//check for required fields from the form
if ((!$_POST[‘username’]) || (!$_POST[‘password’])) {

//connect to server and select database
$conn = mysql_connect(“localhost”, “root”, “password”) or die(mysql_error());
mysql_select_db(“test”,$conn)  or die(mysql_error());

//create and issue the query
$sql = “select f_name, l_name from auth_users where username = ‘$_POST[username]’ AND password = password(‘$_POST[password]’)”;
$result = mysql_query($sql,$conn) or die(mysql_error());

//get the number of rows in the result set; should be 1 if a match
if (mysql_num_rows($result) == 1) {
//if authorized, get the values of f_name l_name
$f_name = mysql_result($result, 0, ‘f_name’);
$l_name = mysql_result($result, 0, ‘l_name’);

//set authorization cookie
setcookie(“auth”, “1”, 0, “/”);

//prepare message for printing, and user menu
$msg = “<P>$f_name $l_name is authorized!</p>”;
$msg .= “<P>Authorized Users’ Menu:”;
$msg .= “<ul><li><a href=\”members1.php\”>secret page</a></ul>”;
} else {
//redirect back to login form if not authorized
<TITLE>members page </TITLE>
<?php print “$msg”; ?>

in a moment you’ll try the script, but now let’s go over what the script is doing:
Line 3 checks for the two required fields from the form. They are the only two fields in the form: username and password. If either one of this fields is not present. the script will redirect the users back to the loign form. If the two fields are present, the script moves along to lines 9, 11, which connect to the database server and select the database to use, in preparation for issuing the SQL query to check the authenticity of the user. This query and its execution, is found in lines 15-16. Note that the query checks the two elements must match each other, and also belong to the username in question, in order to authorize the user. Line 19 test the result of the query by counting the number of rows in the resultset. Then row count should be exactly 1 if the username and password pair represent a valid login. If this is the case the mysql_result() function is used in lines 22-23 to extract the first and lastname of the user. Line 26 sets the authorization cookie. The name of the cookie is auth and the value is set to 1, if a 0 is place in the time slot the cookie will last as long as the users browser session is open. When the user closes the browser the cookie will expire. Line 29-31 create a message for display, including a link to a file we will create next. Finally lines 33-38 handle a failed login attempt. In this case the user is simply redirected back to the login page.

The next figure shows what the user will see upon successful login

and last lets create a scritp that will read the content of the cookie and give access to a private page, once you click on the link that sais secret page…

if ($_COOKIE[‘auth’] == “1”) {
$msg = “<p>You are an authorized user.</p>”;
} else {
//redirect back to login form if not authorized
header(“Location: contact1.php”);
<title>restricted page </title>
<?php print “$msg”; ?>

you could put the previous php snippet to every private page of your web site, so only authenticated users have access to it….

Share This!

Add a Comment

Your email address will not be published.

Sign up for our Newsletter

Download "Google Search Pro"

Enter your email and stay on top of things,