2017-08-01 96 views
0

我寫了一個簡單的php文件來打開使用不同網址的不同網站。 PHP代碼是在這裏。(它的文件名是user.php的)如何使用get方法來執行不同的函數PHP。?

<?php 

$id = $_GET["name"] ; 

if ($id=joe) { 

header('Location: http://1.com'); 
} 

if ($id=marry) { 

header('Location: http://2.com'); 
} 

if ($id=katty) { 

header('Location: http://3.com'); 
} 

?> 

我用這些3種方法來調用PHP文件。

1.http://xxxxxx.com/user.php?name=joe 
2.http://xxxxxx.com/user.php?name=marry 
3.http://xxxxxx.com/user.php?name=katty 

但是PHP文件在每一個time.How只打開http://3.com來解決這個問題? 如何爲每個名稱打開不同的網站?

+0

您的操作符缺少比較'if($ id =='katty')'並將比較值封裝在單引號或雙引號中。 – Dave

回答

1

您的比較錯誤。 joe,marry和katty是字符串類型

<?php 

$id = $_GET["name"] ; 

if ($id=='joe') { //<--- here 

header('Location: http://1.com'); 
} 

if ($id=='marry') { //<--- here 

header('Location: http://2.com'); 
} 

if ($id=='katty') { //<--- here 

header('Location: http://3.com'); 
} 

?> 

這裏是PHP比較運算符的描述。 http://php.net/manual/en/language.operators.comparison.php

+0

@FredGandt,感謝您的指導。 –

1

您應該使用==的條件語句不=

if you use = , you say : 
$id='joe'; 
$id='marry'; 
$id='katty'; 

if($id='katty') return 1 boolean 
1

首先,使用== VS =是什麼地方錯了,你有什麼,但是當你在做一個腳本照顧到不多餘的。您可能還需要考慮作出默認設置應該沒有條件得到滿足:

<?php 
# Have your values stored in a list, makes if/else unnecessary 
$array = array(
    'joe'=>1, 
    'marry'=>2, 
    'katty'=>3, 
    'default'=>1 
); 
# Make sure to check that something is set first 
$id = (!empty($_GET['name']))? trim($_GET['name']) : 'default'; 
# Set the domain 
$redirect = (isset($array[$id]))? $array[$id] : $array['default']; 
# Rediret 
header("Location: http://{$redirect}.com"); 
# Stop the execution 
exit; 
1

所以它看起來像你的問題上面已經回答了,但它可能不適合你說清楚,如果你剛剛開始(使用數組,簡短的PHP if語句等)。

我假設你只是學習PHP考慮你想達到什麼樣的,所以這裏是一個簡單的答案是更容易理解比其他一些人已經張貼在這裏:

<?php 
    // Check that you actually have a 'name' being submitted that you can assign 
    if (!empty($_GET['name'])) { 
     $id = $_GET['name']; 
    } 
    // If there isn't a 'name' being submitted, handle that 
    else { 
     // return an error or don't redirect at all 
     header('Location: ' . $_SERVER['HTTP_REFERER']); 
    } 

    // Else your code will keep running if an $id is set 
    if ($id == 'joe') { 
     header('Location: http://1.com'); 
    } 

    if ($id=marry) { 
     header('Location: http://2.com'); 
    } 

    if ($id=katty) { 
     header('Location: http://3.com'); 
    } 
?> 

希望這可以幫助你更好地理解發生了什麼。

+0

非常感謝。非常明確的解釋 – Thunga