如何在PHP中正确使用header()

How to use header() correctly in PHP

提问人:ᏨᎨᎾᏰᎯᏁᏬ ЯѲβЄЯƬ 提问时间:10/7/2023 更新时间:10/7/2023 访问量:67

问:

我遇到的问题是php中的header('location: ')。我试图将其插入 if 语句中,但不起作用。

我希望被重定向到 example.com,而是返回 404 错误。我考虑过使用其他选项,但我真的很想先尝试使用标题。

<?php
include('login/dbcon.php');
include('login/session.php'); 

$result = mysqli_query($con, "SELECT * FROM users WHERE user_id='$session_id'") or die('Error In Session');
$row = mysqli_fetch_array($result);

if ($row) {

    if ($_SERVER["REQUEST_METHOD"] === "POST") {
        $newRedirectUrl = $_POST["redirectUrl"];
        file_put_contents("customRedirect.txt", $newRedirectUrl);
        echo "Redirect URL updated successfully!";
    }

    echo "
        <h1>Change Redirect URL</h1>
        <form method='POST'>
            <label for='redirectUrl'>New Redirect URL:</label><br>
            <input type='text' name='redirectUrl' id='redirectUrl'><br><br>
            <input type='submit' value='Update'>
        </form>
    ";
} else {
    $redirectUrl = "https://example.com";

    if (file_exists("customRedirect.txt")) {
        $redirectUrl = file_get_contents("customRedirect.txt");
    }
    header("Location: $redirectUrl");
    exit;
}
?>

php if-语句

评论

5赞 Your Common Sense 10/7/2023
如果 example.com 重定向后返回 404,则不是标头函数的问题,而是 example.com 或 URL 的问题。
0赞 ᏨᎨᎾᏰᎯᏁᏬ ЯѲβЄЯƬ 10/7/2023
我试过了,这不是 URL 的问题
0赞 ADyson 10/7/2023
是的。。。因为这就是 404 的意思。您要重定向到的网址不存在。
0赞 FedKad 10/7/2023
你为什么要把剧本放在最后?exit
0赞 ᏨᎨᎾᏰᎯᏁᏬ ЯѲβЄЯƬ 10/8/2023
终止脚本

答:

0赞 SuccoDiMora 10/7/2023 #1

根据 PHP 文档中关于标头函数的注释,您应该注意在标头调用之前不要在输出中发送任何内容。

您可以简单地缓冲输出以避免这种情况:

...
// your if code 
...
$redirectUrl = "https://example.com";
ob_start();
header("Location: $redirectUrl");
ob_end_flush();
exit;

评论

0赞 ADyson 10/7/2023
真。。。但这不是这里发生的事情