W3docs

PHP - setcookie(); not working

There are several reasons why the setcookie() function may not be working.

There are several reasons why the setcookie() function may not be working. Some possible issues include:

  • The setcookie() function must be called before any output is sent to the browser. Make sure that the function is called before any HTML or whitespace is outputted.
    <?php
    // Place at the very top of your script
    setcookie('name', 'value', time() + 3600, '/');
    ?>
  • The path and domain parameters in the setcookie() function may be set incorrectly. Make sure that the path and domain match the settings on your server. Use / for the path to make the cookie available site-wide:
    setcookie('name', 'value', time() + 3600, '/', '.example.com');
  • The browser may have cookies disabled. Ask the user to check their browser settings to ensure cookies are enabled.
  • The cookie name or value may contain invalid characters. Cookie names must be alphanumeric (plus _ and .), and values should not contain commas or semicolons.

It is always helpful to check the return value of the setcookie() function. If the function returns false, you can check the last error by calling error_get_last():

if (!setcookie('test', 'value', time() + 3600, '/')) {
    $error = error_get_last();
    if ($error) {
        echo 'Failed: ' . $error['message'];
    }
}

By verifying header placement, parameter syntax, and return values, you can resolve most setcookie() issues.