I have been using the following code for a while to detect whether or not cookies are enabled but it was just recently discovered that even with browsers set to allow for cookies it wasn't succeeding. It is a simple check on whether or not to rely on cookies in the processing.
We recently migrated to PHP version 5.6.21 but the current setCookie()
documentation doesn't say anything about changing the setcookie approach but makes it clear that if you don't specify anything a blank value is the default. We also get different behavior with PHP version 5.6.10.
Here's another question speaking to this similar issue but does not mention the PHP version being used.
To the documentation's credit, all the examples of setting cookies passes a value (except the deletion part) and here is a note about passing blank:
If the value argument is an empty string, or FALSE, and all other arguments match a previous call to setcookie, then the cookie with the specified name will be deleted from the remote client [emphasis mine]
My interpretation of that is that if the cookie does not exist (no prior call to setcookie with that name) it should create it.
The code:
# Before any html is output:
function cookiesEnabled(){
if(isset($_COOKIE["cookiesEnabled"])){
return true;
}else{
if(isset($_GET["reloaded"])){
return false;
}else{
setcookie("cookiesEnabled" /*,"ANY_VALUE_FIXES"*/);
$query = "";
if($_SERVER["QUERY_STRING"]){
$query = "&".$_SERVER["QUERY_STRING"];
}
header("Location: ?reloaded=1".$query);
exit();
}
}
}
# Check prior to any HTML content being echoed
if(!cookiesEnabled()){
echo "Problem";
} else {
echo "Success";
}
"Success" only appears when a value
parameter is given.
I am content populating a value as a "fix" / "workaround" and I'm glad it seems to work (and is easy) but this question is posed to learn about why the behavior seems to differ from the documentation and hopefully to gain confirmation from someone else.
Our PHP version requiring a value is 5.6.21. I'm not sure what other server settings could be causing this behavior. In a different server with PHP 5.6.10, the value parameter is not required for "Success". When we just upgraded its version to 5.6.21, it also failed.
Does PHP need to update their documentation to explicitly state a value is required or was a coding bug introduced? I don't have any contacts to address either so thanks for forwarding this potential discrepancy to the powers that be.
Note: If I setcookie
like this setcookie("cookiesEnabled", "")
, the result is the same as not passing it (Success in 5.6.10, not in 5.6.21) so at least the documentation probably is defaulting it to "".