Cookies in PHP

Cookies in PHP

A message given to a Web browser by a Web server. The browser stores the message in a text file. The message is then sent back to the server each time the browser requests a page from the server.

Regarding Main Usage on web can be explained as a small collection of information/data, that is stored on the users local computer and is mostly used by websites to identify users who have previously registered or visited the site.

PHP uses the setcookie() function to set cookies.

The syntax

int setcookie (string name [, string value [, int expire [, string path [, string domain [, int secure]]]]])

<?php

setCookie(’user_id’,'2′,0);

?>

The above code set a cookie “user_id” for the current session ie no Time limit is specified if the browsers are closed then cookie will not exist.

If you want to set it for 2 days then you can specify expire into timestamp after days ie : time()+(60*60*24*2)

<?php
setCookie(’user_id’,'2′,time()+(60*60*24*2));

?>

You can get the cookie in the script using $_COOKIE in php script

<?php
echo $_COOKIE[’user_id’];
?>

Note That the server set a cookie on executing setcookie to your local machine
then on every http request your browser will setback the cookie value to the server. So if you try to get the $_COOKIE in the same script you are setting the
cookie you cannot get it.

Leave a Reply

You must be logged in to post a comment.


All material @ copyrighted by chrisranjana.com. If you want to link to this article you are welcome to do so. Unauthorized publication is strictly prohibited. This developer tutorial website contains articles by Php programmers , Software developers, Mysql programmers and asp c# programmers. This website also contains ajax tutorials and advanced mysql sql stored procedures and functions tutorials and sample codes.