A cookie is often a small file that is embedded by the server from which the user has visited or is getting a response. Each time the computer requests a page within a browser, it will send a cookie. Using PHP we can do both create and retrieve cookie values.
A variable is automatically created with the same name that is of the cookie. For example, if a cookie was sent with the name “client”, a variable of name “client” is automatically created containing the cookie i.e $client. Cookies are sent along with the HTTP headers. Like other headers, cookies should be sent before any output from your script.
Create Cookie: The setcookie() function is used to create a cookie. The setcookie() function defines a cookie to be sent along with other HTTP headers. The setcookie() function should be appeared before the <html> and <head> tag.
Syntax:
setcookie(name, value, expire, path, domain, secure, httponly);
Parameters:
- name: It is required. It specifies the name of the cookie to be sent.
- value: It is optional. It specifies the value of the cookie to be sent.
- expire: It is optional. It specifies when the cookie will expire. It has a default value of 0, which determines that the cookie will expire on the closing session (closing the browser).
- path: It is optional. It specifies the server path of the cookie. Its default value is the current directory that the cookie is being set in.
- domain: It is optional. It specifies the domain name of the cookie. For making the cookie available on all subdomains of “example.com”, set it to “example.com”.
- secure: It is optional. It specifies whether cookies should be only transmitted over a secure HTTPS connection. The default value is “false” (cookie will set on any connection).
- httponly: It is optional. If set to TRUE, the cookie will be accessible only through the HTTP protocol. Default is FALSE.
Returns:
- It returns true on success.
- It returns false on failure.
Example 1:
PHP
<?php $value = 'Arecookiesset' ; setcookie( "TestCookie" , $value ); setcookie( "check" , "are cookies set" ) ?> <?php // Print an individual cookie // echo $_COOKIE["TestCookie"] ."\n"; // echo $_COOKIE["check"] ."\n"; // Another way to debug/test is to view all cookies print_r( $_COOKIE ); ?> |
Output:
Array ( [TestCookie] => Arecookiesset [check] => are cookies set )
Example 2: In this example, we are deleting the cookie name “check”.
PHP
<?php $value = 'Arecookiesset' ; setcookie( "TestCookie" , $value ); setcookie( "check" , "are cookies set" ); //deleting the cookie of name check setcookie( "check" , "" ,time()-3600); ?> <?php // Print an individual cookie // echo $_COOKIE["TestCookie"] ."\n"; // echo $_COOKIE["check"] ."\n"; // Another way to debug/test is to view all cookies print_r( $_COOKIE ); ?> |
Output:
Array ( [TestCookie] => Arecookiesset )