0% found this document useful (0 votes)
29 views4 pages

PHP Cookies

Uploaded by

imjyoti1511
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
29 views4 pages

PHP Cookies

Uploaded by

imjyoti1511
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 4

Handling Cookies in PH

A cookie is a piece of information that is stored in the client


browser. Additionally, a cookie is generated on the server and
saved to the client browser
• A cookie is often used to identify a user
• The Cookies are stored on the client side
• A cookie takes less space to store data

The rst time when a client sends a request to the server, the
server embedded the cookie along with the response. Next time
onwards client sends the request along with a cookie to the
server. In such a way, cookies can be received on the server side

A cookie is a small le that the server embeds on the user's


computer. With PHP, we can both create and retrieve cookie
values

Note : Cookie must be used before html tag


fi
.

fi
.

Create cookies with PHP :

setcookie() function is used to set/create cookie

Syntax:

setcookie(name, value, expire);

In the above only the name parameter is required. All other


parameters are optional
Example1:
setcookie("username","StudyGlance");

In the above example, de ning a name and value for cooki

Example2:
setcookie("username","StudyGlance",time()
+1*60*60);

In the above example, de ning a name and value for cookie along
with expiry time (1 hour = 1*60*60 seconds or 3600 seconds

Retrieve a cookie :

$_COOKIE superglobal variable is used to get/retrieve


cookie. i.e Once cookie is set, we can access cookie by
$_COOKIE superglobal variable
Example:
$value = $_COOKIE["username"];

Example1

A simple example to understand working with cookies in PHP


:

fi
fi
.

Example: "cookiedemo.php"

<?php
// To create cookie
setcookie("username", "NETAJI");
?>
<html>
<body>
<?php
if(!isset($_COOKIE["username"])) {
echo "Sorry, cookie is not found!";
} else {
echo "<br/>Cookie Value: " . $_COOKIE["username"];
}
?>
</body>
</html

Output

Once the page has been reloaded


:

>

In the above example program, Firstly cookie is not set. But, if you
refresh the page, you will see cookie is set now. And it creates the
cookie "username" along with the value "NETAJI" and the default
expiry time 0. i,e the cookie will expire as soon as after closing
the browser window
.

You might also like