如何使用get方法来执行不同的函数PHP。?
我写了一个简单的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来解决这个问题? 如何为每个名称打开不同的网站?
您的比较错误。 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
@FredGandt,感谢您的指导。 –
您应该使用==
的条件语句不=
if you use = , you say :
$id='joe';
$id='marry';
$id='katty';
if($id='katty') return 1 boolean
首先,使用==
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;
所以它看起来像你的问题上面已经回答了,但它可能不适合你说清楚,如果你刚刚开始(使用数组,简短的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');
}
?>
希望这可以帮助你更好地理解发生了什么。
非常感谢。非常明确的解释 – Thunga
您的操作符缺少比较'if($ id =='katty')'并将比较值封装在单引号或双引号中。 – Dave