setcookie() is not setting any cookies

833 views Asked by At

This is my first time dabbling in cookies. I couldn't get it to work, so I literally copied and pasted the example from w3schools. On the "try it!" page from their website it works, but when I run the code from my own file on a localhost, it doesn't set the cookie. It outputs "Cookie named 'user' is not set!" every time.

        $cookie_name = "user";
        $cookie_value = "John Doe";
        setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/"); 

        if(!isset($_COOKIE[$cookie_name])) {
            echo "Cookie named '" . $cookie_name . "' is not set!";
        } else {
            echo "Cookie '" . $cookie_name . "' is set!";
            echo "Value is: " . $_COOKIE[$cookie_name];
        }

This is without redirecting the page or anything. It just doesn't set the cookie. I am using Chrome and MAMP. Cookies are enabled in Chrome, and apparently cookies are ON in php.ini as well. I have also tried running it in firefox and safari. Please help me understand

1

There are 1 answers

0
PHPGrandMaster On

setcookie() defines a cookie to be sent along with the rest of the HTTP headers. Like other headers, cookies must be sent before any output from your script (this is a protocol restriction). This requires that you place calls to this function prior to any output, including and tags as well as any whitespace.

Once the cookies have been set, they can be accessed on the next page load with the $_COOKIE array. Cookie values may also exist in $_REQUEST.