• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 207
  • Last Modified:

Set Cookie not working

I created a test page at http://www.cmga.us/test2.php with this code...

-----------------
<?PHP
      print_r($_COOKIE);
      if ( !setcookie("asrf", "asdf", 0) )
            echo '-failed!';
?>
-----------------

It all ways fails... why?
0
JoshWegener
Asked:
JoshWegener
  • 2
  • 2
  • 2
1 Solution
 
geoffreyreemerCommented:
The third variable in a cookie is a time variable. In your example, you are setting a cookie for exactly 0 seconds, which isn't very much of course. Try using the value 3600 there (= 1 hour) and see how it goes then.
0
 
secondvCommented:
^ exactly.

bool setcookie ( string $name [, string $value [, int $expire [, string $path [, string $domain [, bool $secure [, bool $httponly]]]]]] )

http://php.net/setcookie
0
 
JoshWegenerAuthor Commented:
Well, I changed that, but it still fails
0
Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

 
secondvCommented:
Move:

print_r($_COOKIE);

to AFTER trying to set a cookie.
0
 
JoshWegenerAuthor Commented:
it prints out FAILED when it does not work... there is no need to move that. You can also just hit refresh.... because if it did store it in a cookie, it would display the value.
0
 
geoffreyreemerCommented:
Allright mate, I did some tests for you and found out some stuff. This is the right code:

<?php
   if (!setcookie("asrf", "asdf", time()+3600) )
      echo '-failed!';
   print_r($_COOKIE);
?>

Why is this right?

1. It seems you have to add the seconds to the current time when you set a cookie. So it's not just 3600, but time()+3600.
2. You mustn't set a cookie after something has been outputted. Cookies can only be set if there haven't been echo's, prints or other output things. In fact, I even got a genuine "headers already sent" error.

So this will work for you.
0

Featured Post

Get expert help—faster!

Need expert help—fast? Use the Help Bell for personalized assistance getting answers to your important questions.

  • 2
  • 2
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now