函数:header() 适用版本:PHP 4, PHP 5, PHP 7
用法: header(string $header, bool $replace = true, int $http_response_code = null): void
参数说明:
- $header: 必需,指定要发送的HTTP头部信息,格式为"HeaderName: HeaderValue"。
- $replace: 可选,指定是否替换之前的相同类型的HTTP头部信息。默认值为true,表示替换。
- $http_response_code: 可选,指定要发送的HTTP状态码。常见的状态码有200(成功)、404(未找到)等。如果不提供该参数,则默认状态码为200。
示例1:发送简单的HTTP头部信息
header("Content-Type: text/html");
示例2:发送HTTP状态码和重定向
header("HTTP/1.1 301 Moved Permanently");
header("Location: http://www.example.com");
示例3:发送自定义HTTP头部信息
header("X-MyHeader: MyValue");
注意事项:
- header() 函数必须在任何实际的输出之前调用,包括HTML标记、空格和换行符等。
- 如果要发送多个HTTP头部信息,可以多次调用header()函数。
- 如果要发送的HTTP头部信息已经存在,且$replace参数为false,则新的头部信息将会被忽略。
- 如果要发送的HTTP头部信息包含特殊字符(如中文),需要使用urlencode()函数进行编码。
- 在使用header()函数之前,确保没有输出任何内容,否则会导致 "headers already sent" 错误。