Free WebSchools.com

Google




Blog ForumsLive chat WebhostingLink TO UsSEO ToolsResources


HOME

PHP Introduction
Php Installation
PHP Basic Scripts
PHP variables
PHP operators
PHP Conditional statement
PHP functions
PHP Arrays

PHP Objects & classes
PHP with Forms
PHP Files
PHP With Database
PHP session
PHP cookies
PHP Regular Expressions
PHP Server Environment
PHP Graphics
PHP Advance

PHP Cookies


A cookie is often used to identify a user.

What is a Cookie?

Sometimes it becomes necessary to track certain user details like (No. Of Visits, names, last visit, etc). The client machine stores such information and sends it to the web server whenever there is a request. Cookies data are sent along with the HTTP headers.

How to Create a Cookie?

The setcookie() function is used to set a cookie.

Note: The setcookie() function must appear BEFORE the tag.
Syntax
setcookie(name, value, expire, path, domain);
Example
In the example below, we will create a cookie named "user" and assign the value "hari" to it. We also specify that the cookie should expire after an hour:

<?php
setcookie("user", "Alex Porter", time()+3600);
?> Note: The value of the cookie is automatically URLencoded when sending the cookie, and automatically decoded when received (to prevent URLencoding, use setrawcookie() instead).

How to Retrieve a Cookie Value?

The PHP $_COOKIE variable is used to retrieve a cookie value.
<?php
// Print a cookieecho $_COOKIE["name"];// A way to view all cookies
print_r($_COOKIE); ?>

In the following example we use the isset() function to find out if a cookie has been set:



<?php if (isset($_COOKIE["user"])) echo "Welcome " . $_COOKIE["user"] . "!
"; else echo "Welcome guest!
"; ?gt;

How to Delete a Cookie?

When deleting a cookie you should assure that the expiration date is in the past.
Delete example:
<?php // set the expiration date to one hour agosetcookie("user", "", time()-3600); ?>

Difference between session and cookie?

  • The key difference would be cookies are stored in your hard disk whereas a session aren't stored in your hard disk. Sessions are generated at authentication. A session is available as long as the browser is opened.
  • Sessions are popularly used, as the there is a chance of your cookies getting blocked if the user browser security setting is set high.

cookie example