2010-05-22 42 views
0

考虑下面的PHP代码:新手PHP的编码问题:头功能(也许,我需要有人来检查我的代码)

<?php 
$searchsport = $_REQUEST['sport']; 
$sportarray = array(
"Football" => "Fb01", 
"Cricket" => "ck32", 
"Tennis" => "Tn43", 
); 
header("Location: ".$sportarray[$searchsport].".html"); //directs user to the corresponding page they searched 
if ($searchsport == NULL) { 
header("Location: youtypednothing.html"); //directs user to a page I've set up to warn them if they've entered nothing 
} else { 
header("Location: sportdoesnotexist.html"); //if sport isn't in my root, a warning will appear 
} 
?> 

我觉得代码中的注释是不言自明的,基本上当我输入网球场我的form.html它会发送数据到这个php文件并处理,并指导我Tn43.html这是我的网球页面。不幸的是,它不起作用,我真的想知道为什么......(我知道我犯了一个非常愚蠢的错误)。

PS:头是正确的功能,当做一些重定向?

+0

好的,另外一个问题是,这种形式是否有可能被一些坏的屁股攻击呢? – Haskella 2010-05-23 06:10:27

回答

3

你应该重新定位你的代码了一下,修改过:

<?php 
$searchsport = $_REQUEST['sport']; 

$sportarray = array(
"Football" => "Fb01", 
"Cricket" => "ck32", 
"Tennis" => "Tn43", 
); 

if (!$searchsport) { 
header("Location: youtypednothing.html"); //directs user to a page I've set up to warn them if they've entered nothing 
exit; 
} elseif (!in_array($searchsport, $sportarray)) { 
header("Location: sportdoesnotexist.html"); //if sport isn't in my root, a warning will appear 
exit; 
} 

header("Location: ".$sportarray[$searchsport].".html"); //directs user to the corresponding page they searched 
exit; 
?> 
+0

好的...你肯定比我男朋友更有帮助=) 它的工作原理。你能解释为什么吗? – Haskella 2010-05-22 12:43:37

+0

@Haskella:因为你的'if-else'条件错了,要么正在执行,要么永远不会到达你最后的'header'行。那里不需要'else',导致下面的'header'运行,并且低于允许执行的任何内容。 – Sarfraz 2010-05-22 12:44:57

+0

我可以做你的男朋友,哈哈哈,开玩笑吧:) – Sarfraz 2010-05-22 12:47:19

0

我认为你需要在你的头位置的绝对地址:...像http://yoursite.com/youtypednothing.html

+0

我会尝试一下,但会改变什么吗?我所有的东西都在网站的同一个文件夹中。 – Haskella 2010-05-22 12:38:54

+0

我相信相对地址也是允许的:http://ditio.net/2008/10/04/php-redirect-header-location/ – nc3b 2010-05-22 12:41:04

+0

是的,相对不是问题,最终的逻辑是。 – Kzqai 2010-05-22 12:42:04

0

记住头( )不会触发,直到脚本结束或您调用exit()。所以我敢肯定,现在你的代码只说:

(伪)

If null, send to the null page, else send to the default page.

第一次检查将由全包第二的if/else覆盖。

尝试将支票放入带有退出的if/elseif/else块中。

0

您需要检查该密钥是否存在,然后您必须退出if语句。

<?php 
$searchsport = $_REQUEST['sport']; 
$sportarray = array(
"Football" => "Fb01", 
"Cricket" => "ck32", 
"Tennis" => "Tn43", 
); 

if(isset($sportarray[$searchsport])){ 
    header("Location: ".$sportarray[$searchsport].".html"); //directs user to the corresponding page they searched 
    die; 
} else { 
    if ($searchsport == NULL) { 
     header("Location: youtypednothing.html"); //directs user to a page I've set up to warn them if they've entered nothing 
     die; 
    } else { 
     header("Location: sportdoesnotexist.html"); //if sport isn't in my root, a warning will appear 
     die; 
    } 
} 
?> 
+0

这样回声可以指示?死是做什么的? – Haskella 2010-05-22 12:45:53

+0

死亡实际上退出-script-,而不是if语句。通过die或exit退出脚本会触发'header(“Location:something.html”)'语句实际行动。 – Kzqai 2010-05-22 12:56:25

+0

为什么downvote? – 2010-05-22 13:11:13

相关问题