I am trying to diagnose an error in my cookies, but the names of the cookies are not what they should be. Is there a way in PHP to print all the cookies that have been set by my domain?
8 Answers
foreach ($_COOKIE as $key=>$val)
{
echo $key.' is '.$val."<br>\n";
}
-
Hi, this only shows cookies set by me only, what about other cookies (which other websites i,e amazon etc saves in my browser). Please respond– UsmanJul 2, 2017 at 12:25
-
1@Usman That is beyond the scope of the question that was asked. Cookies set by other sites will not be available to your PHP script. If you're asking as a user, try asking in Super User Be sure to specify your OS and Browser.– TecBratJul 2, 2017 at 19:42
echo $_COOKIE["cookie_name"]; // Print an individual cookie
print_r($_COOKIE); // Another way to debug/test is to view all cookies
You can display all cookies defined by running the following php function:
var_dump($_COOKIE);
if($_COOKIE) {
print_r($_COOKIE); //print all cookie
}
else
{
echo "COOKIE is not set";
}
As with any inputs, security practices should include filtering and validation. Since all cookies are strings, sanitize the strings:
var_dump(filter_input_array(INPUT_COOKIE, FILTER_SANITIZE_STRING, FILTER_REQUIRE_ARRAY))
PHP Docs: https://www.php.net/manual/en/function.filter-input-array.php
if($_COOKIE) {
foreach ($_COOKIE as $key=>$val)
{
echo $key.' is '.$val."<br>\n";
}
}
else
{
echo "No Cookies are Set";
}
This will check if any cookies are set, if found will iterate through each and print out the cookie name and value
-
And to access only cookies that I've set manually and to ignore the rest, One approach that you can use is to put all keys into an array in your Php and iterate through $_COOKIE list and check if the keys match and ignore if matched. Nov 18, 2019 at 10:41
echo json_encode($_COOKIE);
for printing all cookies neatly as a json.