PHPheader函数:发送HTTP头部信息
PHP的header函数是用于发送HTTP头部信息的函数。它可以用于向浏览器发送各种头部信息,包括HTTP状态码、Content-Type、Location等。下面是关于PHP header函数的详细说明。
1. 语法:
header(string $header, bool $replace = true, int $http_response_code = null)
参数说明:
- $header:要发送的HTTP头部信息。可以是任何合法的HTTP头部信息,如"Content-Type: text/html"、"Location: http://www.example.com"等。
- $replace:指定是否替换之前已发送的相同类型的头部信息。如果为true(默认值),则替换之前发送的相同类型的头部信息;如果为false,则保留之前发送的相同类型的头部信息,并且新的头部信息将以数组的形式发送。
- $http_response_code:可选参数,用于指定HTTP状态码。如果设置了该参数,则会发送指定的状态码;如果未设置,则会发送默认的状态码。该参数仅在替换已发送的HTTP头部信息时才有效。
2. 返回值:
header函数没有返回值。
3. 例子:
a. 发送文本类型的内容:
header("Content-Type: text/plain");
echo "This is a plain text.";
b. 发送302重定向:
header("Location: http://www.example.com", true, 302);
exit;
c. 发送404页面不存在的状态码:
header("HTTP/1.1 404 Not Found");
echo "404 - Page not found";
4. 注意事项:
a. header函数必须在所有输出之前调用,否则会导致"Cannot modify header information"错误。
b. 只允许发送一个Content-Type头部信息,多个Content-Type头部信息会导致错误。
c. Location头部信息只能用于重定向,必须与状态码302或301一同使用。
d. 使用header函数发送HTTP状态码时,必须在状态码前加上"HTTP/1.1"。
总结:
PHP的header函数是发送HTTP头部信息的重要函数,它可以用于发送各种类型的头部信息,包括Content-Type、Location、HTTP状态码等。使用header函数时要注意调用时机和参数的正确性,以避免错误发生。
