Header menu

_________________________________________________________________________________

Friday, 24 January 2014

Set a cookie / Use a cookie / Discuss a cookie / Explain Cookie


How to set a cookie.

Use setcookie() for setting a cookie.

Example : setcookie('flavor','vanilla');

Calling setcookie()

Cookies are sent with the HTTP headers, so setcookie() must be called before any output is generated. 

Use a Cookie

<?php
// Print an individual cookie
echo $_COOKIE["flavor"]; ?>
 


Arguments to setcookie()

You can pass additional arguments to setcookie() to control cookie behavior. The third argument to setcookie() is an expiration time,expressed as an epoch time- stamp.

Example setcookie('flavor','vanilla',1202075201);

If the third argument to setcookie() is missing ,the cookie expires when the browser is closed.

The fourth argument to setcookie() is a path. The cookie is sent back to the server only when pages whose path begin with the specified string are requested. For example, the following cookie is sent back only to pages whose path begins with   /flavors/

setcookie('flavor','vanilla','','/flavors/');

The page that’s setting this cookie doesn’t have to have a URL that begins with

/flavors/

but the following cookie is sent back only to pages that do.

The fifth argument to setcookie() is a domain. The cookie is sent back to the server only when pages whose hostname ends with the specified domain are requested. 

For example,the first cookie in the following code is sent back to all hosts in the blogspot.com domain,but the second cookie is sent only with requests to the host codesplanet.blogspot.com

1. setcookie('flavor','chocolate chip','','','.blogspot.com');

2. setcookie('flavor','chocolate chip','','','codesplanet.blogspot.com');

If the first cookie’s domain was just blogspot.com instead of .blogspot.com

,it would be sent only to the single host blogpot.com

(and not www.blogspot.com or codesplanet.blogspot.com ).

The last optional argument to setcookie() is a flag that if set to 1 (True),instructs the browser only to send the cookie over an SSL connection. This can be useful if the cookie contains some sensitive information.

Different browsers handle cookies in slightly different ways,especially with regard to how strictly they match path and domain strings and how they determine prioritybetween different cookies of the same name. The setcookie() page of the online manual has helpful clarifications of these differences.

No comments:

Post a Comment