2012-05-22 83 views
0

當用戶登錄時,這裏是我的用戶功能:在PHP中設置的Cookie;但沒有被發現?

public function login($user) { 
    global $database; 
    if ($user) { 

     $_SESSION['user_id'] = $user->id; 
     $this->user_id = $_SESSION['user_id']; 

     $_SESSION['username'] = $user->username; 
     $this->username = $_SESSION['username']; 

     setcookie('user_id', $this->user_id, time() + (60 * 60 * 24 * 14)); 
     setcookie('username', $this->username, time() + (60 * 60 * 24 * 14)); 

     $this->logged_in = true; 

    } 
} 

當我看Cookiees在Chrome中,我找到兩個與此餅乾:
1 USER_ID,1用戶名。

但是,當瀏覽器被關閉,我試圖回來,它不會檢測cookiee:這裏的過程是:

class Session { 

    // Most of the class has been edited out; the code above is also a method in this clas. Removed so it's not duplicated. 


    private $logged_in = false; 
    public $user_id; // yes I realize this is insecure 
    public $username; // yes I realize this is insecure 

    function __construct() { 
      session_start(); 
      $this->check_login(); 
    } 

    public function is_logged_in() { 
     return $this->logged_in; 
    } 

    private function check_login() { 

    if (isset($_COOKIE['user_id']) && (isset($_COOKIE['username']))) { 
     $_SESSION['user_id']= $_COOKIE['user_id']; 
     $_SESSION['username'] = $_COOKIE['username']; 

    } else { // When I test, below shows up showing it doesn't think Cookie is set. 
     echo "Cookie not set in check_login().<br />"; 
    } 

    if (isset($_SESSION['user_id'])) { 
     $this->user_id = $_SESSION['user_id']; 
     $this->username = $_SESSION['username']; 
     $this->logged_in = true; 
    } else { 
     unset($this->user_id); 
     $this->logged_in = false; 

    } 
    } 

$session = new Session(); 

} 
+0

'print_r($ _ COOKIE);'在設置cookie之後,在下一次加載時打印什麼?2)在關閉並重新打開瀏覽器之後? – Czechnology

+0

我登錄後會顯示正確的cookie名稱和值。這:[user_id] => 1 [用戶名] => Joe用戶。它還顯示PHPSESSID和一些Google分析餅乾。當我重新打開瀏覽器。它只顯示Google Cookie。 – KickingLettuce

回答

2

嘗試設置的路徑和域。

setcookie('user_id', $this->user_id, time() + 3600, '/', '.yourdomain.com'); 

如果您將路徑留空,該cookie將僅在當前目錄內處於「活動」狀態。例如,如果您的登錄腳本是http://example.com/user/login.php,那麼當您打開http://example.com時,瀏覽器將不會設置Cookie。

+0

問題:我的登錄名在.domain/folder/HERE中設置了cookie。瀏覽器打開的頁面是一個目錄:.domain/HERE - 那麼我應該使用哪條路徑? – KickingLettuce

+0

我只是想通了。 '/'使其可用於整個域。然後,我不得不更新我的註銷腳本以使其匹配,並且這一切都完美無缺! – KickingLettuce