2012-03-12 39 views
1

在我的login.php頁我有這樣的:PHP頭位置與數組鍵和allowed_operations

$allowed_operations = array('foo', 'lorem'); 
    if(isset($_GET['p']) 
    && in_array(isset($_GET['p']), $allowed_operations)){ 
    switch($_GET['p']){ 
     case 'foo': 
       // Code for 'foo' goes here 
     break; 
     case 'lorem': 
      // Code for 'lorem' goes here 
     break; 
    } 
} 

在哪裏,如果我調用的URL http://example.com/login.php?p=foo功能被調用。

是否有可能我可以在不添加href的情況下調用這個url http://example.com?p=foo在我的html標記中?

例如一些喜歡這樣的:

<?php 

if (array_key_exists("login", $_GET)) { 
    $p = $_GET['p']; 
    if ($p == 'foo') { 
     header("Location: login.php?p=foo"); // This doesn't work 
         // And if I remove the ?p=foo, 
         // it redirect to the page but 
         // the 'foo' function is not called 
     } 
    } 

    ?> 

和我的html:

<a href="?login&p=foo">Login Foo</a> <br /> 
+0

''不應該是''? – mishu 2012-03-12 14:04:17

+0

我知道這就是爲什麼我來這裏問這個問題。我如何在不添加的情況下做到這一點。 – jQuerybeast 2012-03-12 14:06:23

+0

@mishu不,不要緊。 href會自動附加參數到當前的uri,所以定義這兩種方式都是正確的。 – 2012-03-12 14:09:39

回答

1

這是因爲無限頁面的重定向循環。這將由您的代碼創建。

$p = $_GET['p']; 
    if ($p == 'foo') { 
     header("Location: login.php?p=foo"); // This doesn't work 
         // And if I remove the ?p=foo, 
         // it redirect to the page but 
         // the 'foo' function is not called 
     } 
    } 

每次執行該頁面中的狀態將被設置爲true的代碼,也就是$_GET['p']將永遠保存值FOO,它會一次又一次地重定向到同一頁面。檢測哪個PHP將停止執行腳本。

我無法理解您爲什麼要再次重定向到同一頁面,即使條件滿足。我的建議是避免它。只需檢查變量是否想要重定向到同一頁面。如果不是,則跳過該頁面然後重定向到首選目的地。

if (array_key_exists("login", $_GET)) { 
    $p = $_GET['p']; 
    if ($p == 'foo') { 
     //sice the variable foo redirects to the same page skip this path and do nothing 
    } else { 
     //any other url redirection goes here 
     header('Location: index.php?bar'); 
    } 
} 

雖然可能有其他方法。上面的代碼也應該工作,並且會避免進入無限頁面重定向循環。

+0

我知道這就是爲什麼我問如何做到這一點而不添加。 – jQuerybeast 2012-03-12 14:06:00

+0

更新我的答案 – 2012-03-12 14:09:45

+0

更新了答案 – 2012-03-12 15:21:48

0

這裏有一個錯誤:

<a href="?login&p=foo">Login Foo</a> <br /> 

正確:

<a href="login.php?p=foo">Login Foo</a> <br /> 

並且還,循環是無止境的。 當你輸入login.php,然後你要求一次又一次地去...... 第一次後創建一個「休息」功能。

1

我不認爲這是正確的:

$allowed_operations = array('foo', 'lorem'); 
if(isset($_GET['p']) && in_array(isset($_GET['p']), $allowed_operations)){ 

應該

$allowed_operations = array('foo', 'lorem'); 
if(isset($_GET['p']) && in_array($_GET['p'], $allowed_operations)){ 

,你應該使用

<a href="login&p=foo">Login Foo</a> <br /> 

,這是一個無限循環

if (array_key_exists("login", $_GET)) { 
    $p = $_GET['p']; 
    if ($p == 'foo') { 
     header("Location: login.php?p=foo"); // This doesn't work