set cookie in php 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: setcookie php
setcookie($cookiename, $cookievalue, time() + (86400 * 30), "/");
Example 3: cookie are not set in php
setcookie('username',$username,time()+60*60*24*365);
$_COOKIE['username'] = $username;
Example 4: make cookies pph
setcookie("cookiename", "cookievalue", time(), ".mydomain.tld", "/")
Example 5: php set cookie
<?php
$name = 'COOKIE_NAME';
$value = 'VALUE';
$expireTime = strtotime('+1 years');
$path = '/';
setcookie($name,$value,$expireTime,$path);
Example 6: retrieving a cookie in php
$cookiename = $_COOKIE['COOKIE ID']