是否有可能在没有通知客户端处理的情况下使用php重定向?

时间:2014-03-28 08:32:08

标签: php redirect

我们的系统中有很多重定向,适用于php。但是很难将它们删除,因为系统的核心需要它们。

那么,是否有可能在没有在处理第二页时通知客户端并且仅提供第二页内容及其新网址时使用php重定向?

示例:

客户端请求名为page1.php的页面。服务器处理此页面并在处理时意识到需要重定向到page2.php。服务器不会重定向到page2.php,而是运行page2.php的内容,并将page2.php内容发送给客户端。此外,应通知客户实际网址为page2.php

4 个答案:

答案 0 :(得分:2)

您可以使用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;
}

退出是为了停止页面的所有其他呈现。 当没有向用户显示内容时,将后一个代码放在页面顶部,以避免错误。

答案 1 :(得分:1)

听起来你应该修复的东西可能就是重定向。

但是要继续讨论主题,如果你想要摆脱的是第一页加载和第二页(最终目的地)之间的闪烁,这就是我现在所假设的,你可以制作一个相反,AJAX请求内容。

由于您没有分享有关您的架构的任何详细信息,因此很难给出详细信息,但它可能会成为一个重大的重构。通过AJAX获取内容并显示它很容易,如果您使用多个可用框架之一,则更是如此。在所有现代浏览器中也可以通过Javascript更改URL,请参阅其他SO问题:Modify the URL without reloading the page

祝你好运!如果做得好,你可以从中获得好处 - 我们实际上是在Facebook for quite a while做这件事(也许你可以找到一些新的演示文稿)。 The React framework可以帮助前端渲染方面。

答案 2 :(得分:-1)

没关系我以前的回答,似乎我误读了。

您可以使用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脚本之间的无限循环。

答案 3 :(得分:-1)

如果需要重定向

,这就是我在函数中的某个地方
    $redirect_page = "link.php";
    header('Location: ' . $redirect_page);
    exit();