在同一个PHP中使用if-else条件有多个头是否有效


Is it valid to have multiple headers in the same PHP using if-else conditions?

如果希望一个PHP文件根据不同的条件重定向到不同的页面,比如说取决于帖子的结果。。

if(condition 1) {
    header("Location: page1.php");
    exit;
}
else if(condition 2) {
    header("Location: page2.php");
    exit;
}
else {
    header("Location: page3.php");
    exit;
}

真恶心!

您可能需要确保没有先发送邮件头。您可以将headers_sent用于此

if (!headers_sent()) {
  // ...
}

处理这个问题的一个好方法可能是

function redirect_to($location) {
  if (headers_sent($filename, $line)) {
    trigger_error("Headers already sent in {$filename} on line {$line}", E_USER_ERROR);
  }
  header("Location: {$location}");
  exit;
}
// you can now use it like this
if(condition 1) {
  redirect_to("page1.php");
}
else if(condition 2) {
  redirect_to("page2.php");
}
else {
  redirect_to("page3.php");
}

假设您的condition Nif语句是有效的,那么针对不同的情况使用不同的头并没有错。

是的,只要在任何header()调用之前没有输出任何内容。

是的,只要在调用该函数之前不在页面上回显任何内容,就可以了。只要不在头函数的上游打印任何内容,就可以拥有任意多的PHP。