2010-01-15 89 views
-1

在我的網站上,用戶會看到一個yes/no菜單,它決定了他們是否看到它,這是一段代碼。Cookie未保存

if(!isset($_COOKIE['bangUser'])) { 
      // Get createRandomId() method and return a unique ID for the user 
      $unique = ''; 
      // Setting the cookie, name = bangUser, the cookie will expire after 30 days 
      setcookie("bangUser", $unique, time() + (60*60*24*30)); 
      $data['firstTime'] = TRUE; 
     } else { 
      $data['notFirstTime'] = TRUE; 
     } 

如果用戶點擊是,那麼這個運行

function createCookie() { 
     // Function gets called when the user clicks yes on the firstTime menu. 
     // The purpose of this function is to create a cookie for the user. 
     // First we'll give them a unique ID 
     $unique = $this->createRandomId(); 
     // Set an expiration time 
     $expireAt = time() + (60*60*24*30); 
     // With the unique ID now available we can set our cookie doing the same function as before 
     $_COOKIE[] = setcookie("bangUser", $unique, $expireAt); 
     // Now that the cookie is set we can do a 100% check, check that cookie is set and if it is redirect to 
     // to the homepage 
     if(isset($_COOKIE['bangUser'])) { 
      // We need to save the cookie data to the database 
      // First let's load the model for the cookies 
      $this->load->model('cookieModel'); 
      $this->cookieModel->saveCookieRecord($unique, $expireAt); 
      redirect('/welcome'); 
     } 
    } 

如果沒有這個代碼運行,

function createCookieLater() { 
      // Function gets called when the user clicks yes on the firstTime menu. 
      // The of this function is create a cookie for the user, but this time it, 
      // It will expire when the user closes the window. 
      // Again we give them an ID 
      $unique = $this->createRandomId(); 
      $_COOKIE[] = setcookie("bangUser", $unique, 0); 
      // Now that we have set the cookie, we again need to check that it is properly set, 
      // and if it we can redirect the user back to the main page, again. 
      if(isset($_COOKIE['bangUser'])) { 
       // We need to save the cookie data to the database 
       // First let's load the model for the cookies 
       $this->load->model('cookieModel'); 
       $this->cookieModel->saveCookieRecord($unique, $expireAt); 
       redirect('/welcome'); 
      } 
     } 

希望一些能幫助我

回答

4

你真的應該指定存儲Cookie時的域名:

setcookie("bangUser", $unique, time() + (60*60*24*30)); 

應該變成:

setcookie("bangUser", $unique, time() + (60*60*24*30), '/', '.yourdomain.com'); 

我敢肯定,這是你的問題。

+1

+1好吧,比域更多的路徑,我會說。 (如果未設置路徑,將使用當前路徑)。 – 2010-01-15 20:23:09

+0

感謝cballou和Pekka – Udders 2010-01-15 21:12:55