是否有可能用php重定向而不通知客户端在处理


Is there a possibility to redirect with php without inform the client while processing?

我们的系统中有很多重定向,它与php一起工作。但是移除它们是相当困难的,因为系统的核心需要它们。

所以,是否有可能用php重定向而不通知客户端,同时处理第二页,只提供第二页的内容和它的新url?

例子:

客户端请求一个名为page1.php的页面。服务器处理此页面,并在处理过程中意识到需要重定向到page2.php。服务器没有重定向到page2.php,而是运行page2.php的内容并将page2.php的内容发送到客户端。此外,客户端应该被告知,实际的URL是page2.php

您可以使用echo file_get_contents($path_to_page2);获取并回显文件内容,然后在echo 'The actual page is page 2 and can be found...之类的地方放置消息。

$actual_path = '...'; // get this value by a database request I think?
$current_path = ltrim('/', $_SERVER['REQUEST_URI']); // for example (I strip the '/' character because I think you won't use it in the database(?) either.)
if ($actual_path != $current_path) {
    echo file_get_contents($actual_path);
    echo 'The actual file can be found at ...'.$actual_path;
    exit;
}

如果你真的想重定向,只需使用这个;

$actual_path = '...';
$current_path = ltrim('/', $_SERVER['REQUEST_URI']);
if ($actual_path != $current_path) {
    header('Location: '.$path);
    exit;
}

出口用于停止页面的所有其他呈现。当没有内容显示给用户时,将后一段代码放在页面的顶部,以避免出现错误。

听起来您应该首先修复的可能是重定向。

但是为了保持主题,如果您想要摆脱的是第一个页面加载和第二个页面(这是最终目的地)之间的闪烁,这是我假设您现在拥有的,您可以为内容发出AJAX请求。

很难给出具体的细节,因为你没有分享任何关于你的架构的细节,但这可能会是一个大的重构。通过AJAX获取内容并显示它很容易,如果使用可用的多个框架中的一个就更容易了。在所有现代浏览器中,通过Javascript更改URL也是可行的,参考另一个SO问题:修改URL而不重新加载页面

祝你好运!如果做得好,你可以从中得到一些好的东西——我们实际上在Facebook上做了很长一段时间(也许你可以找到一些更新的演示)。React框架可以帮助前端渲染。

我就是这样做的,在函数的某个地方,如果需要重定向

    $redirect_page = "link.php";
    header('Location: ' . $redirect_page);
    exit();

别管我之前的答案了,看来我看错了。

你可以用PHP和HTML5 (Javascript)做你想做的。

您首先需要使用ob_start(), ob_get_contents()ob_end_clean()。(这样你就不会在真正进入你想要的脚本之前抛出内容。

然后,你需要使用HTML5浏览器历史记录工具。

所以在php中:

page1.php

<?php
ob_end_clean();
ob_start();
echo "hello"
if(1){ //oh I need to load page2.php !
    $loading_script = '';// use this to suit your needs https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Manipulating_the_browser_history
    include('header.php');
    include('page2.php');
}
$html = ob_get_contents();
ob_end_clean();
echo $html;
?>

page2.php

<?php
ob_end_clean();
ob_start();
echo "hello 2"
if(0){ //oh I need to load page1.php !
    $loading_script = '';// use this to suit your needs https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Manipulating_the_browser_history
    include('header.php');
    include('page2.php');
}
$html = ob_get_contents();
ob_end_clean();
echo $html;
?>

header。php

<html>
    <script>
        <?=$loading_script?>
    </script>
    <body>

小心在包含php脚本之间的无限循环。