tags:

views:

751

answers:

3

I'm developing on my Mac notebook, I use MAMP. I'm trying to set a cookie with PHP, and I can't. I've left off the domain, I've tried using "\" for the domain. No luck.

setcookie("username", "George", false, "/", false);
setcookie("name","Joe");

I must be missing something obvious. I need a quick and simple solution to this. Is there one?

I'm not doing anything fancy, simply loading (via MAMP) the page, http://localhost:8888/MAMP/lynn/setcookie.php

That script has the setcookie code at the top, prior to even writing the HTML tags. (although I tried it in the BODY as well). I load the page in various browsers, then open the cookie listing. I know the browsers accept cookies, because I see current ones in the list. Just not my new one.

+1  A: 

From the docs:

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.

Is that it?

edit:

Can you see the cookie being sent by the server, e.g. by using the Firefox extension Tamper Data, or telnet? Can you see it being sent back by the browser on the next request? What's the return value of setcookie()? Is it not working in all browsers, or just in some?

Simon
Doesn't appear to be the problem.
lynn
Any blank lines in the PHP script before the setcookie() call? Or perhaps even blank lines before the first <?php ?
Jarret Hardie
Yes!! That was it.
lynn
A: 
<?php
ob_start();
if (isset($_COOKIE['test'])) {
    echo 'cookie is fine<br>';
    print_r($_COOKIE);
} else {
    setcookie('test', 'cookie test content', time()+3600);  /* expire in 1 hour */
    echo 'Trying to set cookie. Reload page plz';    
}

Try this.

SM
A: 

Taking out "localhost" and just having a blank string worked for me.

AllisonC