At first I had my setcookie()
as:
$school = "Some Value";
setcookie("default_school", $school, time()+3600);
var_dump($_COOKIE);
That didn't work, so I did some searching, and found that I probably just needed to set a path, so I changed it to:
$school = "Some Value";
setcookie("default_school", $school, time()+3600, "/", ".mydomain.com");
var_dump($_COOKIE);
That still didn't work so I did some more investigating, and determined that my issue must just me setting the cookie too late. So I then started checking my if my headers were set in certain parts of my code, which needs to return bool(false)
.
var_dump(headers_sent());
First the top of my index.php
, then at the top of my header.php
, but still the same result; they both return true?
I feel like this should be so simple, and I'm getting nowhere. A push in the right direction would be highly appreciated.
Thanks, Isaac
EDIT: Just tried putting it before the init hook, and it returned false. I then put the setcookie function there, and still no luck.
EDIT 2: Ended up adding:
function set_user_cookie() {
$school = "Some Value";
setcookie('default_school', $school, time()+3600);
}
add_action('init', 'set_user_cookie');
and now it works perfectly.
To debug this kind of situation, you should start with enabling proper error reporting (don't use in a production environment):
error_reporting(-1);
ini_set('display_errors', 'On');
If you subsequently call setcookie()
it will issue a warning that will tell you where the output has started.
If you can't do that, you can use headers_sent()
in this manner to figure out where the output has started as well:
if (headers_sent($file, $line)) {
echo "Output started in $file on line $line\n";
}