提问人:ᏨᎨᎾᏰᎯᏁᏬ ЯѲβЄЯƬ 提问时间:10/7/2023 更新时间:10/7/2023 访问量:67
如何在PHP中正确使用header()
How to use header() correctly in PHP
问:
我遇到的问题是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;
}
?>
答:
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
真。。。但这不是这里发生的事情
评论
exit