PHP Cookies
ADVERTISEMENTS
Cookies are a mechanism, which is used to track users of remote browser or identifying return users. Cookies are part of the HTTP header. You can set a cookie with its in-built cookie functions I.e:
setcookie()
setrawcookie()
- cookies must be called before buffering output to the browser by the server, Cookies is used on the client-side.
- During setting any cookie, cookie’s name & cookie’s value also stores in $_COOKIE.
- $_COOKIE is a PHP's predefined server variable, which is used to retrieve cookies.
- Cookies are a small text file that stores on the user’s computer and it’s used to identify users of the server. The cookie creates value by a domain of the server.
- If a cookie is enabled, it is registered as a global variable.
Creating a cookie
setcookie() defines a cookie to be sent along with the rest of the HTTP headers. Like other headers, cookies must be sent before any output from your script (this is a protocol restriction). This requires that you place calls to this function prior to any output, including <html> and <head> tags as well as any whitespace.
setcookie( string $name, string $value = "", int $expires = 0, string $path = "", string $domain = "", bool $secure = FALSE, bool $httponly = FALSE );
Example:
$name = "name";
$value = "David joy";
setcookie($name, $value, time() + 60, '/', domain.com, 1); // this cookie will expire in 60 seconds
setcookie($name, $value, time() + (60*60*24), '/', domain.com, 1); // this cookie will expire in 1 day
Retrieving a cookie
echo $_COOKIE['name']; // it will display 'David joy'
if you want to view all enabled cookies the use this:
print_r($_COOKIE); // it will display all enabled cookie in array form
Modifying a cookie
$name = "name";
$value = "John lee";
setcookie($name, $value, time() + 600, '/', domain.com, 1); // now this cookie will expire in 600 seconds
Deleting a cookie
To delete a cookie you should be set expiration time in setcookie() function, I.e:
setcookie( "name", "", time() - 30 ); // this cookie will expire in 30 seconds