What is: Cookie

A cookie is a small text file that a website can leave in the browser to remember information about the user. It is usually used to identify a returning visitor or to store shopping cart contents, for example. Cookie support is usually enabled in browsers by default, but it can be turned off in the settings.

You can create cookies in PHP and in JavaScript as well.

In PHP with the setcookie() function using the following parameters:

Name: Name of your cookie. Avoid dots, use english alphabet.
Value: The content you want to store. The maximum allowed size of a cookie is usually around 4096 bytes (~= 4096 characters).
Expiration: Optional. The Unix timestamp of expiration. If this value is 0 or not set, cookie will automatically expire when browser is closed.
Path: Optional. Directory where cookie will be available. If this value is omitted, cookie will be available in the directory where it is being set (and its subdirectories). If set to /, it will be available within the entire domain.
Domain: Optional. A cookie is only valid on the host and domain which created it. Here you can set a subdomain that cookie is available to, e.g.: fr.yoursite.com
Security: Optional. If set to true, the cookie will only work with secure HTTPS connection.

<?php
// create a cookie that expires after an hour
// this must happen before printing any output to the browser
if (!isset($_COOKIE['food'])){
    setcookie('food', 'lasagna', strtotime('+1 hour'), '/');
}


// access cookie - you might have to refresh your browser
echo 'My favorite food is ' . $_COOKIE['food'];


// you can delete a cookie by setting a date which has already expired
setcookie('food', '', 1, '/');

 

In JavaScript things are a little bit more complicated. I suggest you to read Mozilla’s guide about cookies.

Recent articles

loading
×