Set cookie wih JS, read with PHP problem

Set cookie wih JS, read with PHP problem

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

Cookie Scope Mismatch: Why Your JavaScript Sets But PHP Can't Read

A common stumbling block when moving between frontend and backend development involves understanding how browsers handle cookie scope. You might successfully set a cookie via JavaScript, only to find it accessible on the client-side of that specific page but invisible to $_COOKIE in another file on the same domain. This isn't necessarily a PHP configuration error or a browser security restriction; it is almost always an issue of attribute mismatch between how the cookie is created and where it is requested.

When you execute document.cookie = "name=value", you are creating a session cookie by default. These cookies live in memory until the browser closes. However, if your goal is to persist data across multiple page loads on the same domain, you must explicitly define an expiration date and a path. Without these attributes, the browser treats the cookie as local to the current execution context for security reasons.

Consider the following JavaScript function designed to set a persistent cookie:

function SetCookie(cookieName, cookieValue, nDays) {
    var today = new Date();
    var expire = new Date();
    if (nDays == null || nDays == 0) nDays = 1;
    
    // Calculate expiration time
    expire.setTime(today.getTime() + 3600000 * 24 * nDays);
    
    // Set the cookie with a specific path and expiration
    document.cookie = cookieName + "=" + escape(cookieValue)
        + ";expires=" + expire.toGMTString();
}

Notice that this function omits the path attribute. While browsers often default the path to the current directory, relying on defaults can lead to subtle bugs. If you set a cookie on /site.com/dashboard, it might only be available when accessing paths starting with /dashboard. When your PHP script resides at /site.com/profile.php, the browser does not send the cookie because the request path does not match the cookie's scope.

To ensure the cookie is available globally across your domain, you must explicitly set path=/ and potentially specify the domain. A robust implementation looks like this:

document.cookie = cookieName + "=" + escape(cookieValue)
    + ";expires=" + expire.toGMTString()
    + ";path=/"
    + ";domain=.site.com"; // Use your actual root domain

On the PHP side, reading the value is straightforward once the scope is correct. You can access it directly in the $_COOKIE superglobal:

// In site.com/profile.php
$value = $_COOKIE['cookieName'] ?? 'Not set';
echo $value;

It is important to note that PHP's default session cookie handling (session.cookie_path) must align with your JavaScript settings. If your application relies on server-side sessions, you may need to ensure php.ini settings like session.cookie_path are configured appropriately, though this rarely affects custom cookies set via headers or script manipulation unless they share the same name.

One frequent mistake developers make is attempting to dynamically insert the domain attribute using server variables within the JavaScript string concatenation in a way that breaks syntax. For example, trying to inject $_SERVER['HTTP_HOST'] directly into a client-side string without proper escaping or context can result in a malformed cookie string. In one instance, a developer attempted to concatenate the path and domain with semicolons, resulting in a malformed attribute list that prevented the browser from storing the cookie at all. The solution was often as simple as removing the redundant or incorrectly formatted parts of the string, ensuring the format strictly adhered to name=value;attribute1=value1;attribute2=value2.

Understanding these nuances prevents frustration when debugging why a value appears in one page but vanishes in another. Always treat cookie attributes as strict contracts: if you don't specify a path, you inherit the browser's default behavior, which might not cover your entire application structure.

Our network