WEB DEVELOPER SITE
HTMLCSSJAVASCRIPTSQLPHPBOOTSTRAPJQUERYANGULARXML
 

PHP 5 Cookies


A treat is regularly used to recognize a user.


What is a Cookie?

A treat is regularly used to recognize a client. A treat is a little document that the server installs on the client's PC. Each time a similar PC asks for a page with a program, it will send the treat as well. With PHP, you can both make furthermore, recover treat values.


Create Cookies With PHP

A treat is made with the setcookie() function.

Syntax

setcookie(name, esteem, lapse, way, area, secure, httponly);

Only the name parameter is required. Every single other parameter are optional.


PHP Create/Retrieve a Cookie

The following model makes a treat named "user" with the esteem "John Doe". The treat will terminate following 30 days (86400 * 30). The "/" implies that the treat is accessible in whole site (generally, select the catalog you prefer).

We then recover the estimation of the treat "client" (utilizing the worldwide variable $_COOKIE). We likewise utilize the isset() capacity to see whether the treat is set:

Example

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

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

</body>
</html>

Note: The estimation of the treat is consequently URLencoded when sending the treat, and consequently decoded when gotten (to avert URLencoding, use setrawcookie() instead).


Modify a Cookie Value

To alter a treat, simply set (once more) the treat utilizing the setcookie() function:

Example

<?php
$cookie_name = "user";
$cookie_value = "Alex Porter";
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/");
?>
<html>
<body>

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

</body>
</html>

Delete a Cookie

To erase a treat, utilize the setcookie() work with a termination date in the past:

Example

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

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

</body>
</html>

Check if Cookies are Enabled

The following precedent makes a little content that checks whether treats are empowered. In the first place, endeavor to make a test treat with the setcookie() work, at that point tally the $_COOKIE cluster variable:

Example

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

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

</body>
</html>