Learn PHP for Developing Web Application

Learn to build web applications with PHP and MySQL, Start your own blog, e-commerce site. In this tutorial you will learn basic, syntax, examples, functions, loops, cookies, sessions, file handling, data connectivity, etc.

PHP Cookies


A cookie is often used to identify a user. A cookie is a small file that the server embeds on the user's computer. Each time the same computer requests a page with a browser, it will send the cookie too. With PHP, you can both create and retrieve cookie values.


PHP setcookie() function

PHP setcookie() function is used to set cookie with HTTP response. Once cookie is set, you can access it by $_COOKIE superglobal variable.

Syntax

bool setcookie ( string $name [, string $value [, int $expire = 0 [, string $path [, string $domain [, bool $secure = false [, bool $httponly = false ]]]]]] )

See this example:

setcookie("CookieName", "CookieValue");/* defining name and value only*/
setcookie("CookieName", "CookieValue", time()+1*60*60);//using expiry in 1 hour(1*60*60 seconds or 3600 seconds)
setcookie("CookieName", "CookieValue", time()+1*60*60, "/mypath/", "mydomain.com", 1);

PHP $_COOKIE

PHP $_COOKIE superglobal variable is used to get cookie.

Example

$value=$_COOKIE["CookieName"];//returns cookie value

PHP Cookie Example

File: cookie1.php
<?php setcookie("user", "Sonoo"); ?> <html> <body> <?php if(!isset($_COOKIE["user"])) { echo "Sorry, cookie is not found!"; } else { echo "Cookie Value: " . $_COOKIE["user"]; } ?> </body> </html>

Output:

Sorry, cookie is not found!

Firstly cookie is not set. But, if you refresh the page, you will see cookie is set now.

Output:

Cookie Value: Sonoo

PHP Delete Cookie

If you set the expiration date in past, cookie will be deleted.

File: cookie1.php
<?php setcookie ("CookieName", "", time() - 3600);// set the expiration date to one hour ago ?>