$_COOKIE (s)

Information for PHP. Hypertext Preprocessor
Post Reply
dzcadii
Posts: 94
Joined: Sun Mar 01, 2015 4:36 am

$_COOKIE (s)

Post by dzcadii » Sun Mar 01, 2015 6:35 pm

Simple way to set a $_COOKIE in php

Code: Select all

<?
//Must be called before any output to the browser or white space
//Note that the $_COOKIE information will be available on the next page (reload)

//setcookie(Cookie name, value(s) held in the cookie, time the cookie will be alive for);

$value = "This is the information set inside of the cookie";
setcookie("This_is_the_cookie_name", $value, time() + 3600);
?>
This is how you kill/delete a cookie

Code: Select all

<?
//Simply set the time to a point in the past
setcookie ("This_is_the_cookie_name", "", time() - 3600);
?>

To simply view the cookie information

Code: Select all

<?
print_r($_COOKIE);
?>
If you want to add information to a $_COOKIE as an array you will have to do the following:

Code: Select all

<?
setcookie("This_is_the_cookie_name[Key_Name_1]","I am value 1 in the cookie array", time() + 3600);
setcookie("This_is_the_cookie_name[Key_Name_2]","I am value 2 in the cookie array", time() + 3600);
setcookie("This_is_the_cookie_name[Key_Name_3]","I am value 3 in the cookie array", time() + 3600);
?>
If you want to see the information in the $_COOKIE as an array

Code: Select all

<?
foreach($_COOKIE['Cookie_Name'] as $key => $value)
{

//*Note* I always use $key => $value because it is clear to understand what part of the array you are using

echo $key . " :: " . $value . "<br>";

}
?>


Here are some examples:
  • As and array
    As an associative array


As an array:

Code: Select all

<?
setcookie("This_is_the_cookie_name[Key_Name_1]","I am value 1 in the cookie array", time() + 3600);
setcookie("This_is_the_cookie_name[Key_Name_2]","I am value 2 in the cookie array", time() + 3600);
setcookie("This_is_the_cookie_name[Key_Name_3]","I am value 3 in the cookie array", time() + 3600);

//If you want to see the information in the $_COOKIE as an array

foreach($_COOKIE['Cookie_Name'] as $key => $value)
{

//*Note* I always use $key => $value because it is clear to understand what part of the array you are using

echo $key . " :: " . $value . "<br>";

}
?>


As an associative array:

Code: Select all

<?
setcookie("This_is_the_cookie_name[Key_Name_1]","I am value 1 in the cookie array", time() + 3600);
setcookie("This_is_the_cookie_name[Key_Name_2]","I am value 2 in the cookie array", time() + 3600);
setcookie("This_is_the_cookie_name[Key_Name_3]","I am value 3 in the cookie array", time() + 3600);

//Call your own array
$Cookie_Data = array();
foreach($_COOKIE as $key => $value)
{
$C_Data[$key] = $value;
}
echo $Cookie_Data['Cookie_Name']['Cookie_Key'];
?>

References:
  1. http://us3.php.net/manual/en/function.setcookie.php

Post Reply