PHP Tutorial: PHP Cookie

PHP Cookie

PHP cookie is a small piece of information which is stored at client browser. It is used to recognize the user.
Cookie is created at server side and saved to client browser. Each time when client sends request to the server, cookie is embedded with request. Such way, cookie can be received at the server side.

Setting a Cookie in PHP
The setcookie() function is used to set a cookie in PHP. Make sure you call the setcookie() function before any output generated by your script otherwise cookie will not set. The basic syntax of this function can be given with:

setcookie(name, value, expire, path, domain, secure);
  • name:    The name of the cookie.
  • value:    The value of the cookie. Do not store sensitive information since this value is stored on the user's computer.
  • expires:    The expiry date in UNIX timestamp format. After this time cookie will become inaccessible. The default value is 0.
  • path:    Specify the path on the server for which the cookie will be available. If set to /, the cookie will be available within the entire domain.
  • domain:    Specify the domain for which the cookie is available to e.g www.example.com.
  • secure:    This field, if present, indicates that the cookie should be sent only if a secure HTTPS connection exists.

Example:

<?php
// Setting a cookie
setcookie("username", "John Carter", time()+30*24*60*60);
?>

Accessing Cookies Values
The PHP $_COOKIE superglobal variable is used to retrieve a cookie value. It typically an associative array that contains a list of all the cookies values sent by the browser in the current request, keyed by cookie name. The individual cookie value can be accessed using standard array notation, for example to display the username cookie set in the previous example, you could use the following code.

<?php
// Accessing an individual cookie value
echo $_COOKIE["username"];
?>

Removing Cookies
You can delete a cookie by calling the same setcookie() function with the cookie name and any value (such as an empty string) however this time you need the set the expiration date in the past, as shown in the example below:

<?php
// Deleting a cookie
setcookie("username", "", time()-3600);
?>

 

Next Topic