PHP Cookie

Posted by tutor | Posted in PHP Tutorial | Posted on 05-08-2010-05-2008

0

A cookie is a small file that the server sends to the client browser, whenever a request is sent. A cookie is often used to identify a user.
The server embeds this cookie on the user’s computer to store some information about the user. Whenever the same computer requests a page, the server sends the cookie too.
Cookies were thought of as a bad thing at the starting, but now nearly all the sites, even the most trusted ones also use cookies. Moreover, today there are more things to worry about.

Creating Cookie
Cookie can be created using the setcookie() function. But remember, the setcookie() function must appear BEFORE the <html> tag.

Syntax

    setcookie(name, value, expiration);

Setcookie() function takes three arguments as:

  • name: The name of your cookie, which will be later on used to retrieve your cookie and the information contained in it.
  • value: The value that is stored in your cookie, generally username(string) and last visit(date).
  • expiration: The date when the cookie will expire and will be deleted. If this parameter is not set, then it will be treated as a session cookie and will be removed when the browser is restarted.

In the example below, we are creating a cookie named “username” and assign the value “Tutor” to it. We also specify that the cookie should expire after one hour:

    For eg:

    <?php
    setcookie(“user”, “Alex Porter”, time()+3600);
    ?>
    <html>

Note: The value of the cookie is automatically URLencoded when sending the cookie, and automatically decoded when received. But to remove this encoding you can use setrawcookie() instead.

You can also set the expiration time of the cookie in another way. It may be easier than using seconds.

    For eg:

    <?php
    $expire=time()+60*60*24*30;
    setcookie(“username”, “Tutor”, $expire);
    ?>
    <html>

In the example above the expiration time is set to a month i.e. 60 sec * 60 min * 24 hours * 30 days.

Write a comment

Twitter Users
Enter your personal information in the form or sign in with your Twitter account by clicking the button below.