setcookie returns 1 but it's not set

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
PaulStat
Forum Newbie
Posts: 2
Joined: Thu May 13, 2010 7:12 am

setcookie returns 1 but it's not set

Post by PaulStat »

Hi Guys,

I'm having issues setting my cookie, I check to see if the cookie is set if not it sets it, problem is it sets it every time! If I echo the result from setcookie it's 1 so I don't understand what's going on?

Code: Select all

<?php
   if(isset($_COOKIE['shoppingcart_id'])) {
      echo "COOKIE IS SET";
   }
   else {      
      //generate a random 10 character code
      $shoppingcart_id = generateId();

     //get the current date
     $today = date("Y-m-d");

     //get the users ip
     $user_ip = $_SERVER['REMOTE_ADDR'];

     //set the lifetime of the cookie
     $expire = time()+(60*60*24*7);

     //set the domain for which the cookie is valid
     $dom = $_SERVER['SERVER_NAME'];
     if($dom[0] == "w"){
        //truncate the first three characters
	$domain = substr($dom, 3);
     }
     else {
        //add point
	$domain = ".".$dom;
     }

     //finally send the cookie to the user agent
     setcookie("shoppingcart_id", $shoppingcart_id, $expire, "/", $domain)
      echo "COOKIE IS NOT SET";
   }
It always goes via the not set route?
PaulStat
Forum Newbie
Posts: 2
Joined: Thu May 13, 2010 7:12 am

Re: setcookie returns 1 but it's not set

Post by PaulStat »

Actually what I've found is If I put the same code on my web server and test it there, it works! Any ideas why that might be?
Post Reply