PHP - Creating Your First PHP Cookie

Creating Your First PHP Cookie.

Cookie in PHP is used to identify a user.

Create a cookie:
Setcookie() can be used for this purpose. It appears before the tag.
setcookie(name, value, expire, path, domain);

Here, a cookie name 'user' is assigned a value 'Sample'. The cookie expires after an hour
setcookie(“user”, “Sample”, time()+3600);

Retrieve a cookie:
The cookie can be retrieved using PHP $_COOKIE variable

Echo the value:
     echo $_COOKIE["user"];

Creating Your First PHP Cookie.

A cookie is created by using setCookie() function. This function takes 3 arguments:

Name – The name of the cookie to be used to retrieve the cookie.

Value - The value is persisted in the cookie. Usually, user names and last visit date / time are used

Expiration – The date until which the cookie is alive. After the date the cookie will be expired. If the expiry date is not set, then the cookie is treated as a default cookie and will expire when the browser restarts.


//Set 60 days as the life time for the cookie.
//seconds * minutes * hours * days + current time
$inTwoMonths = 60 * 60 * 24 * 60 + time();
setcookie('lastVisit', date("G:i - m/d/y"), $inTwoMonths);

PHP - When would you use htmlentities?
When would you use htmlentities? - HTMLENTITIES disallows users to run malicious code in HTML....
PHP - E-mail With PHP
E-mail With PHP - PHP uses its inbuilt mail() function to send emails from the script...
PHP - How Sessions Work?
How Sessions Work? - When a user logs in an application, his details are usually stored in a session variable.....
Post your comment