Best practice for setting/checking PHP Cookies

PHP cookies are great tools, when used properly (and implemented properly). 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. This means  your $_COOKIE value will not be set until you refresh, or go to another page. So I explored the Googlesphere for a fair chunk of time, and discovered the best practice for setting/checking PHP cookies within the same page load (no redirect).

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:

setcookie( 'my_cookie_name', $my_cookie_value, time() + 60*60*24*30, '/' );
$my_cookie = $my_cookie_value;

or

$my_cookie = $my_cookie_value;
setcookie( 'my_cookie_name', $my_cookie, time() + 60*60*24*30, '/' );

or (if you are just storing true/false)

$my_cookie = setcookie( 'my_cookie_name', true, time() + 60*60*24*30, '/' );

Checking for your cookie later in the page

if( isset( $my_cookie ) || isset( $_COOKIE['my_cookie_name'] ) ) {
// do stuff
}

There you have it, the best practice for setting/checking PHP Cookies. If anyone has other methods/practices, please comment!

Leave a Reply

Your email address will not be published. Required fields are marked *