How can I set and check a cookie in PHP?

buzzbuzz
buzzbuzz asked this question

I would like to check on a users visit if a cookie is set and if not to set this cookie.

Answers
Danny 1 year ago Hey There!

Take a look at the following snippets (taken from w3schools - http://www.w3schools.com/php/php_cookies.asp), hope this helps :)

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

<?php
// Check Cookie
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];
}
?>

Leave A Reply


You may use these HTML tags and attributes:<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strong>