PHP and Cookies

Xpert

202.***.***.***
1,430 days ago

PHP and Cookies

Overview: In this article we will discuss about cookies and how to make cookies work with PHP.

What the heck are cookies?
A cookie can hold small collection of information/data, that is stored on the users local computer and is mostly used by websites to identify users who have previously registered or visited the site.

We will be using the setcookie() function provided in PHP to set cookies.

The syntax for setcookie() function:

int setcookie (string name [, string value [, int expire [, string path [, string domain [, int secure]]]]])

Looks confusing let me give you an example to simplify things!

Setting a Cookie

<?php
$site_name = "PHPbuddy.com";
setcookie("first_cookie",$site_name,time()+604800);
?>

In the above example we have created a cookie with the name first_cookie which contains the value "PHPbuddy.com", the cookie has an expiry time of 1 weeks means that the cookie will be automatically deleted after one week. Okay that 604800 is 1 week in sec!


Reading data from Cookies: Now that we have made a cookie, I will show you how to read data stored in the cookie, there are three methods to reterive cookies.

$site = $first_cookie // Not recommended
$site = $HTTP_COOKIE_VARS["first_cookie"]; //Recommended
$site = $_COOKIE["first_cookie"]; // Recommended but requires PHP 4.1


I personally like the 2nd one. The first method relies on PHP to search through every possible variable and finally find the cookie and can be used by name. However with 'register_globals' off in the PHP configuration file would cause the cookie to fail. Instead using the second will always allow your scripts to run. This gets the cookies name out of the specified cookies variables which makes it a lot faster and reliable. The third method is the best, folks at PHP group tell you to use this method although it requires PHP 4.1 and above to work.

Deleting a cookie

It is good to delete a cookie manually from your site. All you do is set the same cookie but with no value and with an expiry date in the past. This forces the browser to delete the cookie from the users system. Below is how we'd delete our first_cookie cookie from the users system:

<?php
setcookie ("first_cookie", "", time()-60000);
?>

As shown, the value is empty and the expiry date is the current time() minus 60000 seconds, Any negative number will work but due to variations in computer times, it is not recommended to use -1 but instead something higher like a day or two.

phool4fool

203.***.***.***
1,417 days ago

Cookies a quick glance

Cookies a quick glance
What is a cookie?
Sometimes it becomes necessary to track certain user details like (No. Of Visits, names, last visit, etc). The client machine stores such information and sends it to the web server whenever there is a request. Cookies data are sent along with the HTTP headers. You can look at this URL to know more about how they work. http:\www.cookiecentral.comfaq

Difference between session and cookie?

The key difference would be cookies are stored in your hard disk whereas a session aren't stored in your hard disk. Sessions are basically like tokens, which are generated at authentication. A session is available as long as the browser is opened.
Sessions are popularly used, as the there is a chance of your cookies getting blocked if the user browser security setting is set high.
Note: When you issue a session_start() it generates a session ID and places that on the client side in a cookie. There are also some ways to avoid this using the tag rewrite.

How secure is storing password using cookies?

Generally we store the cookies with the username followed by the password. Now we can use any algorithm to encrypt the password before we store then to make it secured. Now we will have the user name and encrypted password stored in the cookie, which again can be played around. A good practice would be to avoid the storing of user name and using a unique ID generated. This is a overhead which we have to compromise to make thinks more secure.

PHP Cookie Function

As told earlier cookie is sent along with the HTTP headers and to do this we have the set_cookie() function.
boolean setcookie ( string name [, string value [, int expire [, string path [, string domain [, int secure]]]]] )
All the arguments except the name argument are optional. If only the name argument is present, the cookie by that name will be deleted from the remote client. You may also replace any argument with an empty string ("") in order to skip that argument. The expire and secure arguments are integers and cannot be skipped with an empty string. Use a zero (0) instead. The expire argument is a regular Unix time integer as returned by the time() or mktime() functions. The secure indicates that the cookie should only be transmitted over a secure HTTPS connection.
Courtesy: www.php.net

Common Errors

Warning: Cannot modify header information - headers already sent by....

Always ensure there are no white spaces or HTML tags before the cookie function. When you start with a blank line in your PHP file there is a possibility of getting this error.

Quick Code.

This example will allow you to save user name and password on the client PC as cookie and retrieve them when needed.

There are totally three “.php” files used and let me give a short introduction about what they do.

Index.php

This page initially checks whether the cookie has been created or not. If the cookie is created it displays the name and password stored in it.

Login.php

This page is showed when the cookie isn’t created. The user has to select the checkbox if he needs his details to be remembered.

Logout.php

This page deletes the cookie that has been created.

Now I haven’t concentrated much on the design aspect and this tutorial is to demonstrate how cookies are implemented. You may have to redo the entire code to implement it with your site. I hope this doesn’t bother you much.

index.php Code

PHP Example: (!)

PHP code:

<?php
//Check if cookie is set
if (!isset($_COOKIE['cookie_info']))
{
echo $_COOKIE['cookie_info'];
?>


<body>
<form method="POST" action="login.php">
<br><br><br><br><br><br><br>
<center><h1>Cookies </h1>
<Center>
<table border="0" width="auto">
<tr>
<td width="33%">Login Name</td>
<td width="33%"><input type="text" name="name" size="20"></td>
<td width="34%"> </td>
</tr>
<tr>
<td width="33%">Password</td>
<td width="33%"><input type="password" name="pass" size="20"></td>
<td width="34%"><input type="checkbox" name="set" value="ON">Remember Me</td>
</tr>
</table>
<center>
<p><input type="submit" value="Submit" name="sub">
<input type="reset" value="Reset" name="res"></p>
</center>
</body>
</form>

PHP code:

<?php }
else
{
//Cookie is set and display the data
$cookie_info = explode("-", $_COOKIE['cookie_info']); //Extract the Data
$name = $cookie_info[0];
$pass = $cookie_info[1];
echo "<center><h3>Welcome back $name and your password is $pass";
echo "<a href='logout.php'>Logout</a>";
exit;
}
?>



$_COOKIE or $HTTP_COOKIE_VARS is a super global variable which is used to retrieve the data. Once the cookie is set I retrieve the data, which is stored in it. I have used “-“ as delimiter for each field i.e (name-password).

login.php Code

PHP Example: (!)


PHP code:

<?php
if(empty($_POST['name']) || empty($_POST['pass']))
{ ?>
<b>Fill All Details </b>
<?php exit;
}
else
{
//Colllect the details and validate
$time = time();
$name = $_POST['name'];
$pass =md5($_POST['pass']);
$check = $_POST['set'];
$db = mysql_connect("localhost", "admin","admin") or die(mysql_error());
mysql_select_db("test",$db) or die(mysql_error());
$query = "select * from Login where name='$name' and password='$pass'";
$sql = mysql_query($query) or die(mysql_error());
$count = mysql_num_rows($sql);

if ($count == 1)
{
$cookie_data = $name.'-'.$pass;
if($check=='ON')
{
if(setcookie ("cookie_info",$cookie_data, $time+3600)==TRUE)
{
echo "Cookie SET".$cookie_data; ?>
<a href='logout.php'>Logout</a>

<? }
}
}
else
{
echo "Authentication Failed";
exit;
}

}
?>



The above code authenticated the user and also if the user has opted to save the password and name we store them in a cookie. The password is encrypted using md5 and is concatenated with “-“ hyphen as field separator. Now the $cookie_data variable contains the concatenated string. The setcookie function is used to store the data into a cookie. The first argument is the cookie reference name (in this example “cookie_info”). The second argument is the data that is to be stored and the third would determine how long the cookie is valid. .
In the example the cookie lifetime is set to 1 hour. Now you must be wondering how? The time () function returns the current Unix time stamp. For example “1072724721” actually means Mon, 29 Dec 2003 19:05:21 UTC. Now lets add a 3600 to the Unix time stamp 1072724721 + 3600 = 1072728321 this is actually Mon, 29 Dec 2003 20:05:21 UTC. You need to spend bit of your time looking at mktime and time functions to understand this better. A cookie returns TRUE on successful creation. .

logout.php Code

PHP Example: (!)

PHP code:

<?php
$time = time();

if (isset($_COOKIE['cookie_info']))
{
setcookie ("cookie_info", "", $time - 3600);
echo "Logged Out";
}

echo $time;
?>



Destroying a cookie is quite simple and you might also find that we again use the same function for this. Now you might see me subtracting 3600 what do I really mean by this? I am actually rewinding the clock and setting a old time to it. When I subtract 3600 it rewind my clock one hour before. So if you had created a cookie at 9 AM I will set it to 8 AM there by meaning the cookie has expired. I hope I didn’t sound complex. .

Conclusion

I guess the cookies scare has gone after reading this tutorial. Cookies are simple and it’s always a matter of time for you to understand. So right now all you need to practice a bit to get used to what you have learned. Post in your comments and suggestions for me to know what I sounded like.

Bradd

203.***.***.***
1,412 days ago
These are some good posts about cookies review but i think there is nothing to worry about cookies here .In other languages like ASP i always get all properties about cookies on pressing a single dot and i think always in all coding languages all of that features are availabale