2010-01-14 60 views
1

我目前在我的網站中使用cookie,我做的第一件事就是檢查用戶是否有cookie,如果他們不顯示菜單,如果他們點擊3個選項它創建一個cookie,但如果然後退出瀏覽器中的cookie被破壞,這裏是我的代碼,當瀏覽器退出時,Cookie被破壞

function createRandomId() { 
    $chars = "abcdefghijkmnopqrstuvwxyz023456789"; 
    srand((double)microtime() * 1000000); 
    $i = 0; 
    $unique = ''; 
    while ($i <= 7) { 
     $num = rand() % 33; 
     $tmp = substr($chars, $num, 1); 
     $unique = $unique.$tmp; 
     $i++; 
    } 
    return md5($unique); 
} 

function index() { 
    // $data is the array of data that is passed to views, setup it up 
    $data = array(); 
    // We need to setup the cookie that will be used site, this will be used to cross reference 
    // The user with the options they have selected, to do this we first need to load the session model 
    // Check if the user has a cookie already, if they it means they have been to the site in the last 30 days. 
    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; 
    } 

    // Load the view and send the data from it. 
    $this->load->view('base/index', $data); 
} 


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(); 
    // With the unique ID now available we can set our cookie doing the same function as before 
    setcookie("bangUser", $unique, time() + (60*60*24*30)); 
    // 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'])) { 
     redirect('welcome'); 
    } 
} 

基本上指數()函數檢查和的createCookie創建一個新的cookie,任何人可以看到任何問題?

+1

您應該使用'uniqid()'而不是創建自己的,較慢的'createrandomid()'函數。 – ryeguy 2010-01-14 15:13:29

回答

1

在你createCookie的功能,調用setCookie方法不會值立即添加到$ _COOKIE超全局 - 這陣只持有目前cookie時提出請求(但你可以存儲新的cookie值)

此外,如果您希望在瀏覽器退出時銷燬會話cookie,請將過期時間指定爲null。另外,只需使用PHP的內置會話。

1

您需要將setcookie($ path)的第四個參數設置爲您網站的絕對路徑。例如:

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