Sunday, December 15, 2024

Using Cookies with PHP

Share

Using cookies in PHP is a fairly easy task. As you know, you can store information in a cookie that can be used later on.

Cookies are used to remember information regarding the user and his or her preferences without using the database. Cookies can also remember the login information. Storing the passwords while using cookies is not recommended but if you want the user name field of the form to be filled automatically, you can save this value in a cookie and retrieve it when the user reloads the page. For the current example, let’s assume that there is a login form on a page. It goes something like this:

<form method="post" name="f1? action="login.php">
Enter user name: <input type="text" name="uname" size="30? /><br>
Enter password: <input type="password" name="password" size="30? /><br>
<input type="submit" name="s1? value="Submit" />
</form>

The real cookie-related action takes place in login.php. The code in this file first checks in the database whether correct user name and password were entered, and if yes, assuming a variable $user_name stores the correct user name, it gets stored in a cookie in the following manner:

setcookie("stored_user_name", $user_name, time()+60*60*24*30);

This is really plain. A cookie named “stored_user_name” is created and the value of $user_name is stored in it. The 3rd argument is the duration after which it is going to expire. Here time() + 60*60*24*30 means a month from now. There are other parameters too but on an average you only get to deal with these 3 things.

Now, going back to the form defined above. We’ll need to re-write it in order to enable it to use the stored value in the cookie. This is how it is done:

if($HTTP_COOKIE_VARS["stored_user_name"]!="")
{
           $stored_name=$HTTP_COOKIE_VARS["stored_user_name"];
}
else
{
            $stored_name="";
}

<form method="post" name="f1? action="login.php">
Enter user name: <input type="text" name="uname" size="30? value="<?php print $stored_name; ?>" /><br>
Enter password: <input type="password" name="password" size="30? /><br>
<input type="submit" name="s1? value="Submit" />
</form>

You need to take care of one thing though; $HTTP_COOKIE_VARS[] only performs before any text output appears on your web page. Ideally, you should check for the existence of a cookie value before all those <HTML> and <HEADER> tags, i.e., just beneath the session_start() function.

Amrit Hallan is a freelance copywriter,
and a website content writer. He also dabbles
with PHP and HTML. For more tips and tricks in
PHP, JavaScripting, XML, CSS designing and
HTML, visit his blog at
http://www.aboutwebdesigning.com

Table of contents

Read more

Local News