在 PHP 中发送标头
使用 header 函数时,最好在一个地方动态确定协议,这样我们就不必编辑发送 headers 的所有位置,以防我们以后更改协议。
$protocol = $_SERVER["SERVER_PROTOCOL"]; //Determine the protocol $supported_protocols = array( 'HTTP/2.0' => true, 'HTTP/1.1' => true, 'HTTP/1.0' => true, ); $protocol = $_SERVER["SERVER_PROTOCOL"]; if (!isset($supported_protocols["$protocol"])) { $this->protocol = 'HTTP/1.0'; }
要在 PHP 中执行重定向,我们可以使用 header 函数。
假设我们从当前请求的页面重定向到 /other-page,我们可以这样做:
header($protocol . ' 303 See Other'); header('Location: http://onitroad.com/other-page');
标头应该始终在任何输出之前发送,例如由 echo、print 或者通过使用“?>”退出 PHP 产生的输出,否则我们可能会收到“标头已发送”错误。
HTTP Location 标头告诉浏览器加载另一个页面,通常在执行 301 重定向时使用。
通常,当使用位置标头时,还会发送 HTTP 状态代码,例如 303 See Other。
可以发送 HTTP 位置标头以响应与已移动内容匹配的任何请求。
浏览器应自动将请求传递到此标头中指示的位置。
虽然相对路径可能适用于某些客户端,但建议使用带有位置标头的绝对路径。
$supported_protocols = array( 'HTTP/2.0' => true, 'HTTP/1.1' => true, 'HTTP/1.0' => true, ); $this->protocol = $_SERVER["SERVER_PROTOCOL"]; if (!isset($supported_protocols["$protocol"])) { $protocol = 'HTTP/1.0'; } //Send the Headers header($protocol . ' 303 See Other'); header('Location: http://onitroad.com/other-page');
日期:2020-06-02 22:17:27 来源:oir作者:oir