[英]PHP Redirect to different url using header("Location:") does not work
我对 php 很陌生,我做了一些研究并尝试了其他人的解决方案,但它对我没有用。 我想在执行特定代码后将用户重定向到另一个页面。 我意识到没有错误消息,并且站点没有更改。 所以我从代码中删除了几乎所有内容并将其放入一个小的 test.php 文件中。 同样的问题仍然存在。
<!DOCTYPE html>
<html>
<body>
<h1>Tes2</h1>
<?php
// Execute some code here
sleep(10); // Give the user 10 seconds to read the output of my code
// redirect the user with php or trigger a JS script to do that
header("Window-target: _parent");
header("Location: https://www.w3schools.com/");
?>
</body>
</html>
期望:该页面应该执行主要的 php 脚本(由注释可视化)并触发一个计时器。 当计时器结束时,它应该将我重定向到“www.w3schools.com”。 应该没有错误或其他消息。 重定向应该由 php 代码完成,如果可能的话(JS 可能是解决这个问题的一种方法,但我仍然需要在我的 php 代码执行后启动 JS 代码)。
结果:页面显示并加载 html 代码。 该网站保持不变。 没有错误。
环境:在 Linux Mint(64 位)的 Chromium 版本 96.0.4664.45(Offizieller 构建)上运行该网站正常运行,并且确实按预期执行了 PHP 代码,但不是这个。
是否有一个轻量级和通用的(对于大多数流行的浏览器)解决方案可以将用户重定向到另一个页面?
必须在传输任何数据之前设置标题,因此您不能将它们粘贴在文件中间。 引用手册:
请记住,必须在发送任何实际 output 之前调用header() ,无论是通过普通的 HTML 标记、文件中的空行还是来自 PHP。
因此,至少您需要将文件重写为:
<?php
header("Window-target: _parent");
header("Location: https://www.w3schools.com/");
?>
<!doctype html>
...
此外,永远不要在 http(s) 响应中sleep()
:无论它需要生成什么内容,该响应都应该尽可能快地完成。 睡眠在(实际上任何)PHP 代码中没有位置。
PHP 和 JS 的组合似乎是最简单的解决方案。 但这可能只是我的看法。 我试图尽可能地记录代码,以便其他人可以理解:
<?php
function redirect() { // Create some JS code which will pause for 3 seconds and execute the move function afterwards. This Function will redirect the user
echo "<script>";
echo "function move() {window.location.replace('http://www.w3schools.com');}";
echo "setTimeout(move, 3000);";
echo "</script>";
}
?>
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<h1>Test2</h1>
<?php
echo "<p>You will be redirected after the code has been executed!</p>";
// Run actual code
redirect(); // Redirect using JS code
?>
</body>
</html>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.