How to set cookies using PHP and get them via JavaScript

Arthur Streeton - Sydney (1921), panoramic painting of sunlit city buildings, parkland and harbour

I had an application where I wanted to set a cookie value using PHP’s setcookie() function and then read it out later in JavaScript. The problem is that setcookie() URL-encodes the value the same way urlencode() does, turning spaces into +. JavaScript’s decodeURIComponent() follows standard percent-encoding rules and leaves plus signs alone, so a string like abc cdf comes back as abc+cdf.

Setting the cookie in PHP

When I first wrote this post back in 2013, my workaround was to call str_replace('+', '%20', urlencode($string)) before passing the result to setrawcookie(). That works, but PHP already has rawurlencode(), which uses %20 for spaces from the start. Pass that encoded string to setrawcookie() so PHP sends it as-is instead of URL-encoding it a second time:

setrawcookie('cookie', rawurlencode($string), [
    'expires' => time() + 3600 * 24 * 7,
    'path' => '/',
    'secure' => true,
    'httponly' => false,
    'samesite' => 'Lax',
]);

Like setcookie(), you have to call this before any HTML or other output is sent to the browser. A few things to keep in mind with those options:

  • PHP 7.3 or later: Passing the options as an associative array (which is also how you set samesite) requires PHP 7.3+.
  • secure => true: Browsers will only store and send a Secure cookie over HTTPS (aside from local development on localhost).
  • httponly => false: This is set to false because JavaScript needs to read the cookie. Never do this for session or authentication cookies – keep httponly set to true on anything sensitive so JavaScript cannot read it.
  • samesite => 'Lax' and no domain: Leaving out domain locks the cookie to the current host rather than sharing it across subdomains, and SameSite=Lax restricts cross-site sending while still allowing normal top-level navigation.

Two other PHP quirks can catch you out here. First, if $string is an empty string (""), setrawcookie() treats that as a request to delete the cookie rather than store an empty value. Second, make sure the string is valid UTF-8 and well under the 4 KB cookie size limit (keep in mind rawurlencode() turns every space or non-ASCII byte into three characters).

Reading the cookie in JavaScript

In the browser, JavaScript reads cookies from document.cookie as a semicolon-separated string. Split on ;, trim each entry, look for the exact name= prefix so you don’t accidentally match another cookie with a similar name, and run the value through decodeURIComponent():

function getCookie(name) {
    const prefix = `${name}=`;
    const match = document.cookie
        .split(';')
        .map(part => part.trim())
        .find(part => part.startsWith(prefix));

    if (match === undefined) {
        return null;
    }

    try {
        return decodeURIComponent(match.slice(prefix.length));
    } catch {
        return null;
    }
}

const value = getCookie('cookie');

Slicing after prefix.length (instead of splitting on =) keeps any = characters intact if another cookie wasn’t encoded, and the try/catch stops a tampered or malformed % sequence from throwing a URIError.

Reading the cookie back in PHP

If you later want to read the cookie back on the server, do not call urldecode() on $_COOKIE. PHP already URL-decodes incoming cookies automatically when it populates $_COOKIE – something I got wrong in the original version of this post. Calling urldecode() a second time mangles the data by turning literal + characters into spaces and double-decoding any literal %20 sequences.

Just read $_COOKIE directly, and check that you actually got a string (a client sending Cookie: cookie[]=... turns $_COOKIE['cookie'] into an array):

$string = is_string($_COOKIE['cookie'] ?? null) ? $_COOKIE['cookie'] : '';

Of course, all the usual warnings about not trusting user-supplied data remain. Just because your script created the cookie does not mean what comes back from the browser hasn’t been modified – always validate the value before you use it, escape it if you output it to a page, and keep anything that needs to be tamper-proof on the server instead.

Hopefully this saves someone some time.

Filed under Development PHP

Leave a comment

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