May 10 2013
Best practice for setting/checking Cookies
In a recent WordPress project, I created a semi-basic Poll form. Because WP uses actions, I was able to detect that my form ran, and updated my Poll Results in the database. In the SAME page load, however, you cannot check your $_COOKIE node for your cookie. PHP Globals are not altered (besides $_SESSION) except for when the page first loads, so your $_COOKIE value will not be set until you refresh, or go to another page.
The practice to check for your value is quite simple – when you set your cookie, set it to a global variable as well. That way you do not have to force a refresh/redirect to get your $_COOKIE value.
Setting the Cookie:
1 2 |
setcookie( 'my_cookie_name', $my_cookie_value, time() + 60*60*24*30, '/' );
$my_cookie = $my_cookie_value;
|
or
1 2 |
$my_cookie = $my_cookie_value;
setcookie( 'my_cookie_name', $my_cookie, time() + 60*60*24*30, '/' );
|
or (if you are just storing true/false)
1 |
$my_cookie = setcookie( 'my_cookie_name', true, time() + 60*60*24*30, '/' );
|
Checking for your cookie later in the page
1 2 3 |
if( isset( $my_cookie ) || isset( $_COOKIE['my_cookie_name'] ) ) {
// do stuff
}
|
