What are cookies in PHP?

Last updated 6 years ago | 1618 views 75     5

Tags:- PHP

PHP | What are cookies in PHP?

A cookie is a small piece of information store by the browser on the client location and sent to the server with every request. It stores a limited amount of data about 4kb(i.e.: 4096 bytes).

 

Create Cookies

A cookie is created with the setcookie() function.

setcookie(name, value, expire, path, domain, secure, httponly)

Parameters

Parameter Description Which type of data
name Name of the cookie. String
value Value of the cookie, stored in the client's computer. String
expire Unix timestamp, i.e. number of seconds since January 1st, 1970 (called as Unix Epoch). Integer
path Server path in which the cookie will be available. String
domain To which domain the cookie is available. String
secure If set true, the cookie is available over a secure connection only. Boolean
httponly If set true, the cookie is available over HTTP protocol only. Scripting languages like JavaScript won't be able to access the cookie. Boolean

Create/Retrieve a Cookie

<?php
$cookie_name = "user";
$cookie_value = "Devid Brooks";
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/"); // 86400 = 1 day
?>
<html>
<head>Create/Retrieve a Cookie Example</head>
<body>

<?php
if(!isset($_COOKIE[$cookie_name])) {
  echo "Cookie named '" . $cookie_name . "' is not set!";
} else {
  echo "Cookie Name is:'" . $cookie_name . "'<br>";
  echo "Cookie Value is: " . $_COOKIE[$cookie_name];
}
?>

</body>
</html>

 

Note: The setcookie() function must appear BEFORE the <html> tag.

Note: The value of the cookie is automatically URLencoded when sending the cookie, and automatically decoded when received (to prevent URLencoding, use setrawcookie() instead).


Modify a Cookie Value

To modify a cookie, just set (again) the cookie using the setcookie() function:

<?php
$cookie_name = "user";
$cookie_value = "Brono";
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/"); // 86400 = 1 day
?>
<html>
<head>Modify a Cookie Value Example</head>
<body>

<?php
if(!isset($_COOKIE[$cookie_name])) {
  echo "Cookie named '" . $cookie_name . "' is not set!";
} else {
  echo "Cookie Name is:'" . $cookie_name . "'<br>";
  echo "Cookie Value is: " . $_COOKIE[$cookie_name];
}
?>

</body>
</html>

Delete a Cookie

To delete a cookie, use the setcookie() function with an expiration date in the past:

<?php
// set the expiration date to one hour ago
setcookie("user", "", time() - 3600);
?>
<html>
<head>Cookie Delete Example</head>
<body>

<?php
echo "Cookie 'user' is deleted.";
?>

</body>
</html>

Check if Cookies are Enabled

Below creates a small script that checks whether cookies are enabled.

<?php
setcookie("test_cookie", "test", time() + 3600, '/');
?>
<HTML>
<head>Check if Cookies are Enabled</head>
<body>

<?php
if(count($_COOKIE) > 0) {
  echo "Cookies are enabled.";
} else {
  echo "Cookies are disabled.";
}
?>

</body>
</html>