使用switch case改变php头文件


Change php header using switch case

我想根据组合框中选择的字符串重定向到其他页面。

我添加了以下代码:

switch ($downloadType){
    case "text1":
        header("Location:pdf/text1.pdf");
        break;
    case "text2":
        header("Location:pdf/text2.pdf");
    case "text3":
        header("Location:pdf/text3.pdf");
    default:
        header("Location:index.html");
}

但是这个简单的脚本不起作用。我是php的新手。你知道为什么我不能改变标题吗?是不是我们不能用switch-case语句来改变header ?

如果不是这样的话,那么在表单提交时重定向到另一个页面的方法是什么呢?

你需要添加一个break;到每个case的末尾。

case "text3": 
    header("Location:pdf/text3.pdf"); 
    break;

你需要添加break:

switch ($downloadType){
case "text1":
    header("Location:pdf/text1.pdf");
    break;
case "text2":
    header("Location:pdf/text2.pdf");
    break;
case "text3":
    header("Location:pdf/text3.pdf");
    break;
default:
    header("Location:index.html");
}

必须将switch语句看作是一种跳转到结构。根据求值表达式的值,代码执行跳转到第一个适当的casedefault语句,并从那里继续执行。这就是为什么大多数情况下您需要插入break语句的原因。目前,您只对"text1"情况执行此操作。

除此之外,我建议您在组成Location HTTP头时使用完整的url,即使相对url通常按预期工作。HTTP规范实际上不允许使用相对url。

header('Location: http://example.com/foo/pdf/text2.pdf');

不要忘记发送HTTP头文件并不会停止脚本的执行。完成后添加一个exit;语句。

除了使用break完成case语句外,还必须记住在发送任何实际输出之前必须调用header()。

例句:

<html>
<?php
header("Location:pdf/text2.pdf");?>
</html>

将不工作,因为" <html> "行已经被发送到客户端,排除了header()的使用。基本上,在尝试调用header()之前,请确保文件中没有输出。

编辑:裁判:http://php.net/manual/en/function.header.php