且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

带有 Post 参数的 PHP 重定向

更新时间:2023-11-17 08:19:10

您可以通过标头重定向 POST 请求,并包含 POST 信息.但是,您需要显式返回 HTTP 状态代码 307.浏览器将 302 视为使用 GET 重定向,忽略原始方法.这在 HTTP 文档中明确指出:

You CAN header redirect a POST request, and include the POST information. However, you need to explicitly return HTTP status code 307. Browsers treat 302 as a redirect with for GET, ignoring the original method. This is noted explicitly in the HTTP documentation:

实际上,这意味着在 PHP 中您需要在重定向位置之前设置状态代码:

Practically, this means in PHP you need to set the status code before the redirect location:

    header('HTTP/1.1 307 Temporary Redirect');
    header('Location: anotherpage.php');

但是,请注意,根据 HTTP 规范,用户代理必须询问用户是否可以将 POST 信息重新提交到新 URL.实际上,Chrome 不会询问,Safari 也不会询问,但 Firefox 会向用户显示一个确认重定向的弹出框.根据您的操作限制,这可能没问题,但在一般使用情况下,它肯定有可能给最终用户造成混淆.

However, note that according to the HTTP specification, the user agent MUST ask user if they are ok resubmitting the POST information to the new URL. In practical terms, Chrome doesn't ask, and neither does Safari, but Firefox will present the user with a popup box confirming the redirection. Depending on your operating constraints, maybe this is ok, although in a general usage case it certainly has the potential to cause confusion for end users.