PHP | Basic Cookie Concept

What is Cookie ?

Cookies are used to store the information of a web page in a remote browser, so that when the same user comes back to that page, that information can be retrieved from the browser itself.Cookies are a mechanism for storing data in the remote browser and thus tracking or identifying return users. Cookies are text files stored on the client computer and they are kept of use tracking purpose.

cookie is often used to identify a user. A cookie is a small file that the server includes on the user’s computer. Each time the same computer requests a page with a browser, it will send the cookie too. With PHP, you can both create and retrieve cookie values.

How to set cookie in PHP ?

A cookie is created with the setcookie() function.

syntax  : setcookie ( name, value, expire, path, domain, secure, httponly ) ;

parameter name is required in this function, other are optional .

Example For Set Cookie :

<?php

$name1 = "nametest1";
$value1 = "valuetest1";
setcookie($name1 , $value1 , time() + (86400 * 30), "/");
 ?>

Cookie set always before html code.

How To Retrieve Cookie ?

As per above example,

<?php

echo $_COOKIE ["$name1"];

?>

Output is : nametest1

How To Delete Cookie ?

As per above example,

<?php
// set the expiration date to one hour ago
setcookie("nametest1", "", time() - 3600);

?>

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *