php的header函数怎么使用

PHP的header()函数用于向浏览器发送原始的HTTP头信息。它通常用于重定向页面、设置响应状态码、设置缓存等操作。

语法:

header(string $header, bool $replace = true, int $http_response_code = null)

参数说明:

$header:要发送的头信息,可以是一个字符串,也可以是一个包含多个头信息的数组。

$replace:可选参数,指定是否替换之前发送的相同类型的头信息,默认为true,表示替换。

$http_response_code:可选参数,设置响应状态码。

示例:

设置重定向:

header("Location: http://www.example.com");

设置响应状态码:

header("HTTP/1.1 404 Not Found");

设置缓存:

header("Cache-Control: no-cache, must-revalidate");

注意事项:

在调用header()函数之前不能输出任何内容,包括空格和换行符,否则会导致“headers already sent”错误。

可以通过ob_start()函数开启输出缓冲区来解决“headers already sent”错误。

阅读剩余
THE END