PHP重定向回用户所在位置


PHP Redirect Back To Where User Was

假设我有这个脚本:

http://www.example.com/profile.php?uid=12345

在这个脚本中,有一个由sendmessage.php处理的发送消息功能。sendmessage.php实际做的是向数据库中插入一些内容,然后重定向回用户开始的位置(profile.php?uid=1345)。

我尝试使用标题("Location:profile.php")。

但是既然profile.php需要?URL中的uid=1234[而且是动态的],我的重定向计划不起作用。

如何"传递"当前URL。在我的例子中是profile.php?uid=1234'使用GET方法发送message.php。然后,一旦sendmessage.php完成处理,就将用户发送回他们自己的屏幕(profile.php?uid=1345)?

提前谢谢。

在您的profile.php?uid=12345中,如果您使用表单将数据发送到sendmessage.php然后你可以有一个隐藏的字段,比如-

<input type="hidden" name="redirect_to" value="<?=$_SERVER['REQUEST_URI']?>">

然后在sendmessage.php中,您可以使用header("Location: ".$_REQUEST['redirect_to']);

试试这个:

header("Location: " . $_SERVER['HTTP_REFERER']);

PHP.net注释:

The address of the page (if any) which referred the user agent to the current page. This is set by the user agent. Not all user agents will set this, and some provide the ability to modify HTTP_REFERER as a feature. In short, it cannot really be trusted.

一个技巧是在链接中填充信息,这样当你转到另一个页面时,这些参数仍然存在。。。如果您愿意,可以使用param作为以前的url。

另一个选项是确保将uid作为表单提交数据的一部分发送。

然后,您可以使用传入的值重建URL:

header("Location:profile.php?uid=".$_GET["uid"]);

或者,将用户ID存储在会话中。这样,它在$_SESSION["uid"]中总是可用的,并且您不必记住在表单中创建一个无关的字段。

您应该将变量传递给类似的sendmessage.php

sendmessage.php?uid=<?php echo (isset($_GET['uid']) ? (INT)$_GET['uid'] : 'default') ?>

然后在sendmessage.php上。使用类似的东西

header("Location: profile.php?uid=" . (isset($_GET['uid']) ? (INT)$_GET['uid'] : 'default') ); 

您可以使用GET和一些javascript。使用此方法可以避免使用PHP的头函数时出现的问题。

echo "<script type='"text/javascript'"> window.location = '"profile.php?uid=" . $_GET["uid"] .    "'"</script>";

请确保检查"uid"是否确实已通过。您还可以在用户第一次登录时将uid存储在会话变量中,然后在我的示例中使用它,从而避免了必须使用GET。无论哪种方式都有效。