PHP 5 Cookies
What is cookies?
A cookie is a small amount of data/text files stored by the user's browser itself. Whenever the browser requests a page on your Web site, all the data in the cookie is automatically sent to the server within the request.
- Maximum size of cookies are 4KB.
- Browsers can store up to 30 cookies per Web site domain
- You can set a cookie for a fixed amount of time
The content of a cookies
A cookies contain more than simply name and value. In fact cookies has seven parameter that can be passed to it.
- The name of the cookies
- The value of cookies
- The expiration time of the cookies
- The path of the cookies
- The domain name of the cookies
- Secure connection need to use the cookies
Creating cookies using PHP
Cookies can be set using build in method setcookie
|Name||The name of the cookie|
|Value||The value of the cookie|
|Expires||The time that the cookie should expire|
|Path||The path that the browser should send the cookie back to|
|Domain||domain by default, a browser only sends a cookie back to the exact computer that sent it|
|Secure||A secure connection to be set (default to 0; to enable this feature set this 1)|
All the parameter except name are optional.
Where cookies are used?
Cookies are generally used in different web application. Some of them are listed below
- Shopping cart application
- Online banking
- Fee based service
- Website tracing
Setting cookies using setcookies();
setcookie( "TestCookie" , $value );
setcookie( "TestCookie" , $value , time()+3600 ); /* expire in 1 hour */ setcookie( "TestCookie" , $value , time()+3600 , "http:\\www.ptutorial.com" , true); /*secure */
setcookie( "Test" , "john" , $time1 , "/" , "uk.com" ,"true" );
Expiration time to be set for five days, and secure connection are used.
Accessing Cookies using PHP
echo $_COOKIE["test"];//Single cookies
// View all cookies
echo "Welcome " . $_COOKIE["TestCookies"];
echo "Sorry... Not recognized" ;
isset() check cookies submit or not.
Destroying Cookies using PHP
$value = 'something from somewhere';
setcookie("TestCookie", $value, time()-3600);
Where cookies are place
By default all the generated cookie are store on the HDD of user’s local machine. Different version of the operating system keep cookies in different location.
Locate cookies using browser:
1. Open internet explorer click tools ->internet option as shown in diagram
2. Internet option dialog box appear as shown in diagram
3. From internet options dialog box click setting as shown in diagram
4. Temporary internet files folder path is shown in setting dialog box as shown in diagram
5. Now you can locate the cookies