2013-01-05 142 views
2

我正在嘗試編寫一個調試腳本來測試我的cookie,但由於某種原因,它總是運行腳本來刪除所有的cookie,即使條件未滿足時也是如此。這裏是我的代碼 - 這是所有HTML和PHP:爲什麼我的「if」語句總是被確定爲TRUE?

<form id="cookietest" name="CookieTest" method="post"> 
    <input type="submit" name="createcookie" value="Create cookie" /> 
    <input type="submit" name="removecookie" value="Remove cookie" /> 
    <input type="submit" name="removeallcookies" value="Remove all cookies" /> 
</form> 
<?php 
    $Domain = thedomain.com 
    if($_POST['createcookie'] == TRUE) 
    { 
     $expire = 60*60*24*14 + time(); 
     setcookie('TestCookie', 'IExist', $expire, '/', $Domain); 
     echo 'TestCookie should have been created. See its value below.<br />'; 
    } 
    if($_POST['removecookie'] == TRUE) 
    { 
     $expire = time() - 60*60*24*14; 
     setcookie('TestCookie', 'IExist', $expire, '/', $Domain); 
     echo 'TestCookie should have been deleted. See its value below.<br />'; 
    } 
    if($_POST['removeallcookies'] == TRUE); 
    { 
     $expire = time() - 60*60*24*14; 
     setcookie('TestCookie', 'IExist', $expire, '/', $Domain); 
     setcookie('Cookie1', '', $expire, '/', $Domain); // destroys persistent cookie 
     setcookie('Cookie2', '', $expire, '/', $Domain); // destroys persistent cookie 
     setcookie('Cookie3', '', $expire, '/', $Domain); // destroys persistent cookie 
     echo 'All specified cookies should have been removed. <br />'; 
    } 
    if($_POST['createcookie'] == FALSE && $_POST['removecookie'] == FALSE) 
    { 
     echo 'Neither the cookie create nor cookie remove button was clicked.<br />'; 
    } 
    echo "The contents of 'TestCookie':"; 
    echo "${_COOKIE['TestCookie']}<br />"; 
    echo "The cookie array<br />"; 
    echo "<pre>"; 
     print_r($_COOKIE); 
    echo "</pre>"; 
?> 
+5

使用'如果(isset($ _ POST [ '字段名']){...}' –

回答

5

你後添加semi-colon if條件,這就是爲什麼你如果不執行

if($_POST['removeallcookies'] == TRUE); //<<< semi-colon 
+0

謝謝!它總是簡單的東西,導致最壞的問題... – Adam11

+0

@ knoell8504:好吧,它有時會發生 –

+0

我認爲你的意思是塊總是執行,而不是。分號會導致塊始終執行,而不是阻止它。 – MrCode

3

塊我認爲你應該使用isset,而不是隻一個==

if(isset($_POST['createcookie'])) 
{ 
} 
+0

是的,我已經看到了很多。究竟是這樣做的原因是什麼? – Adam11

+0

** $ _ POST ['createcookie'] **將等於「創建cookie」,輸入中的名稱值是$ _POST中的鍵,值是值(至少我認爲是這樣) – ZombieSpy

0

由於@Cthulhu說改用:

檢查,它被設置:

if(isset($_POST[index])){ 


// do something 

} 

檢查,它不設置:

if(!isset($_POST[index])){ 


// do something 

}