php cookie code example
Example 1: php cookies
//Cookies
//Cookies are stored on the client side. cookies are not as secure as sessions
//and it is recommended that you use sessions as much as possible.
====================
Version 1 for cookies
====================
<?php
if(isset($_COOKIE['nameofcookie'])){
echo 'User ' . $_COOKIE['nameofcookie'] . ' is set<br>';
}else{
echo'User is not set';
}
====================
Version 2 for cookies
====================
<?php
setcookie('nameofcookie','Frank', time() + (86400 *30));
if(isset($_COOKIE['nameofcookie'])){
echo 'User ' . $_COOKIE['nameofcookie'] . ' is set<br>';
}else{
echo'User is not set';
}
=======================
Version 3 for cookies
=======================
<?php
setcookie('nameofcookie','Frank', time() + (86400 *30));
setcookie('nameofcookie','Frank', time() -3600);
if(isset($_COOKIE['nameofcookie'])){
echo 'User ' . $_COOKIE['nameofcookie'] . ' is set<br>';
}else{
echo'User is not set';
}
=========================
Version 4 check for cookies
=========================
<?php
setcookie('nameofcookie','Frank', time() + (86400 *30));
if(count($_COOKIE) > 0){
echo 'There are ' . count($_COOKIE) . ' cookies saved<br>';
}else{
echo 'There are no cookies saved<br>';
}
if(isset($_COOKIE['nameofcookie'])){
echo 'User ' . $_COOKIE['nameofcookie'] . ' is set<br>';
}else{
echo'User is not set';
}
Example 2: make cookies pph
setcookie("cookiename", "cookievalue", time(), ".mydomain.tld", "/")
Example 3: php cookies
//Cookies
//Cookies are stored on the client side. cookies are not as secure as sessions
//and it is recommended that you use sessions as much as possible.
//save addional information as an array in a cookie
<?php
$user = ['name' => 'Brad', 'email' => '[email protected]', 'age' = 35];
$user = serialize($user);
setcookie('user', $user, time() + (86400 *30));
$user = unserialize($_COOKIE['user']);
echo $user['name'];
Example 4: php cookies
//Cookies
//Cookies are stored on the client side. cookies are not as secure as sessions
//and it is recommended that you use sessions as much as possible.
<?php
if(isset($_POST['submit'])){
$username = htmlentities($_POST['username']);
setcookie('nameofcookie', $username, time()+3600);
header('Location: page2.php');
}
?>
<!DOCTYPE html>
<html>
<head>
<title>PHP Cookies</title>
</head>
<body>
<form method="POST" action="<?php echo $_SERVER['PHP_SELF'];?>">
<input type="text" name="username" placeholder="Enter Username">
<br>
<input type="submit" name="submit" value="Submit">
</form>
</div>
</body>
</html>
Example 5: retrieving a cookie in php
$cookiename = $_COOKIE['COOKIE ID']
Example 6: php cookie
setcookie ('name', 'value', $expiresOn, $path, $domain, $secure, $httponly)