codescracker


php

PHP Cookies



« Previous Tutorial Next Tutorial »


A cookie in PHP, is often used in identifying the users on the web.

PHP5 Cookie

A cookie is basically a small file that the server embeds on the user's computer to identify the user on next, visiting the same page.

Create Cookies using PHP

You are free to create cookies using setcookie() function in PHP. Here is the general form to create cookie in PHP:

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

Here are the parameters are option, except the parameter name.

PHP Create/Retrieve Cookie Example

Here is an example, creates a cookie named "user" with the value "Satyam Pandey". The cookie will expire after 30 days (86400 * 30). The "/" means that the cookie is available in entire website (otherwise, select the directory you prefer)

We then retrieve the value of the cookie "user" (using the global variable named $_COOKIE). We also use the function named isset(), to find out if the cookie is set or not:

<!DOCTYPE html>
<?php
$cookie_name = "user";
$cookie_value = "Satyam Pandey";
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/"); // 86400 = 1 day
?>
<html>
<body>

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

</body>
</html>

Delete Cookie using PHP

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

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

</body>
</html>

Check if Cookies are Enabled or Not using PHP

<!DOCTYPE html>
<?php
setcookie("test_cookie", "test", time() + 3600, '/');
?>
<html>
<body>

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

</body>
</html>

« Previous Tutorial Next Tutorial »



Tools
Calculator

Quick Links
Signup - Login - Give Online Test