search

header

(PHP 3, PHP 4, PHP 5)

header -- 发送一个原始 HTTP 标头

说明 void  header ( string string [, bool replace [, int http_response_code]] )

header() 函数用来发送一个原始 HTTP 标头。有关 HTTP 标头的更多内容见 HTTP/1.1 规范。

可选参数 replace 指明是替换掉前一条类似的标头还是增加一条相同类型的标头。默认为替换,但如果将其设为 FALSE 则可以强制发送多个同类标头。例如:

header('WWW-Authenticate: Negotiate');
header('WWW-Authenticate: NTLM', false);
?>

第二个可选参数 http_response_code 强制将 HTTP 响应代码设为指定值(此参数是 PHP 4.3.0 新加的)。

有两种特殊的 header 调用。第一种是标头以字符串“HTTP/”(大小写不重要)开头的,可以用来确定要发送的 HTTP 状态码。例如,如果配置了 Apache 用 PHP 来处理找不到文件的错误处理请求(使用 ErrorDocument 指令),需要确保脚本产生了正确的状态码。

header("HTTP/1.0 404 Not Found")
?>

注: HTTP 状态码标头行总是第一个被发送到客户端,而并不管实际的 header() 调用是否是第一个。除非 HTTP 标头已经发送出去,任何时候都可以通过用新的状态行调用 header() 函数来覆盖原先的。

第二种特殊情况是以“Location:”标头。它不只是把这个标头发送回浏览器,它还将一个 REDIRECT(302)状态码返回给浏览器,除非之前已经发出了某个 3xx 状态码。

header("Location: http://www.example.com/"); /* 重定向浏览器 */

/* 确保重定向后,后续代码不会被执行 */
exit;
?>

注: HTTP/1.1 标准需要一个绝对地址的 URI 做为 Location: 的参数, 但有一些客户端支持相对 URI。通常可以使用 $_SERVER['HTTP_HOST']、$_SERVER['PHP_SELF'] 及 dirname() 函数来自己从相对 URI 产生出绝对 URI:

<?phpheader("Location: http://".$_SERVER['HTTP_HOST']                        . rtrim(dirname($_SERVER['PHP_SELF']), '/\\')                       ."/".$relative_url);?>

注: 即使启用了 session.use_trans_sid,Session ID 也不会随着 Location 头信息被传递。必须手工用 SID 常量来传递。

PHP 脚本通常会产生一些动态内容,这些内容必须不被浏览器或代理服务器缓存。很多代理服务器和浏览器都可以被下面的方法禁止缓存:

header("Cache-Control: no-cache, must-revalidate"); // HTTP/1.1
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); // 过去的时间
?>

注: 可能会发现即使不输出上面所有的代码,网页也没有被缓冲。用户有很多选项可以设置来改变浏览器的默认缓存行为。通过发送上述标头,应该可以覆盖任何可以导致脚本页面被缓存的设置。

另外,当使用了 session 时,利用 session_cache_limiter() 函数和 session.cache_limiter 选项可以用来自动产生正确的缓存相关标头。

要记住 header() 必须在任何实际输出之前调用,不论是来自普通的 HTML 标记,空行或者 PHP。有一个常见错误就是在通过 include(),require() 或一些其它的文件存取类函数读取代码时,有一些空格或者空行在调用 header() 之前被发送了出去。同样在一个单独的 PHP/HTML 文件中这个错误也很普遍。


/* 这将产生一个错误,因为在调 header()
* 之前已经输出了东西 */
header('Location: http://www.example.com/');
?>

注: 自 PHP 4 起,可以通过一些输出缓冲函数来解决这个问题。代价是把所有向浏览器的输出都缓存在服务器,直到下命令发送它们。可以在代码中使用 ob_start() 及 ob_end_flush() 来实现这样的功能,或者通过修改 php.ini 中的 output_buffering 配置选项来实现,也可以通过修改服务器配置文件来实现。

如果想提示用户保存所发送的数据,例如一个生成的 PDF 文件,可以通过发送 Content-Disposition 标头提供推荐的文件名来强制浏览器弹出一个保存文件对话框。

// 这样将会直接输出一个 PDF 文件
header('Content-type: application/pdf');

// 这样做就会提示下载 PDF 文件 downloaded.pdf
header('Content-Disposition: attachment; filename="downloaded.pdf"');

// 这是 original.pdf 的源文件
readfile('original.pdf');
?>

注: Microsoft Internet Explorer 4.01 中的一个漏洞使得该机制无法正常工作,无解决方案。在 Microsoft Internet Explorer 5.5 中也有个漏洞影响到这一点,升级到 Service Pack 2 或更高版本可以解决。

注: 在安全模式下,如果设定了 WWW-Authenticate 标头(用于 HTTP 认证)则脚本的 UID 会添加到其中的 realm 部分中去。

---------------------------------------------------------------------------------------

// 服务器错误
header('HTTP/1.1 500 Internal Server Error');

// 重定向到一个新的位置
header(‘Location: http://blog.iterse.com/’);
//用这个header指令来解决URL重写产生的404 header
header(‘HTTP/1.1 200 OK’);

// 页面没找到
header(‘HTTP/1.1 404 Not Found’);

// 访问受限
header(‘HTTP/1.1 403 Forbidden’);

// The page moved permanently should be used for
// all redrictions, because search engines know
// what’s going on and can easily update their urls.
//页面被永久删除,可以告诉搜索引擎更新它们的urls
header(‘HTTP/1.1 301 Moved Permanently’);

// 延迟一段时间后重定向; 也可以使用HTML语法来实现延迟
header(‘Refresh: 3; url=http://blog.iterse.com/’);
echo ‘You will be redirected in 3 seconds’;

// 加载要下载的文件:
header(‘Content-Transfer-Encoding: binary’);
readfile(‘example.zip’);

// 设置内容类型:
header(‘Content-Type: text/html; charset=iso-8859-1′);
header(‘Content-Type: text/html; charset=utf-8′);
header(‘Content-Type: text/plain’); // plain text file
header(‘Content-Type: image/jpeg’); // JPG picture
header(‘Content-Type: application/zip’); // ZIP file
header(‘Content-Type: application/pdf’); // PDF file
header(‘Content-Type: audio/mpeg’); // Audio MPEG (MP3,…) file
header(‘Content-Type: application/x-shockwave-flash’); // Flash animation
?>

-----------------------------------------------------------------------------

在PHP中用header("location:test.php")进行跳转要注意以下几点:
1、location和“:”号间不能有空格,否则会出错。
2、在用header前不能有任何的输出。
3、header后的PHP代码还会被执行。
下面是和asp中重定向response.redirect的比较:
例1:
response.redirect "../test.asp"
header("location:../test.php");
两者区别:
asp的redirect函数可以在向客户发送头文件后起作用.




查是php中下例代码会报错:


header("location:../test.php");
?>

只能这样:

header("location:../test.php");
?>
...
即header函数之前不能向客户发送任何数据.

例2:
asp中


response.redirect "../a.asp"
response.redirect "../b.asp"
%>

结果是重定向a.asp文件.
php呢?

header("location:../a.php");
header("location:../b.php");
?>

我们发现它重定向b.php.
原来在asp中执行redirect后不会再执行后面的代码.
而php在执行header后,继续执行下面的代码.
在这方面上php中的header重定向不如asp中的重定向.有时我们要重定向后,不能执行后面的代码:
一般地我们用
if(...)
header("...");
else
{
...
}
但是我们可以简单的用下面的方法:
if(...)
{ header("...");exit();}
还要注意的是,如果是用Unicode(UTF-8)编码时也会出现问题,需要调整缓存设置.

 

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
11 Best PHP URL Shortener Scripts (Free and Premium)11 Best PHP URL Shortener Scripts (Free and Premium)Mar 03, 2025 am 10:49 AM

Long URLs, often cluttered with keywords and tracking parameters, can deter visitors. A URL shortening script offers a solution, creating concise links ideal for social media and other platforms. These scripts are valuable for individual websites a

Introduction to the Instagram APIIntroduction to the Instagram APIMar 02, 2025 am 09:32 AM

Following its high-profile acquisition by Facebook in 2012, Instagram adopted two sets of APIs for third-party use. These are the Instagram Graph API and the Instagram Basic Display API.As a developer building an app that requires information from a

Working with Flash Session Data in LaravelWorking with Flash Session Data in LaravelMar 12, 2025 pm 05:08 PM

Laravel simplifies handling temporary session data using its intuitive flash methods. This is perfect for displaying brief messages, alerts, or notifications within your application. Data persists only for the subsequent request by default: $request-

Build a React App With a Laravel Back End: Part 2, ReactBuild a React App With a Laravel Back End: Part 2, ReactMar 04, 2025 am 09:33 AM

This is the second and final part of the series on building a React application with a Laravel back-end. In the first part of the series, we created a RESTful API using Laravel for a basic product-listing application. In this tutorial, we will be dev

Simplified HTTP Response Mocking in Laravel TestsSimplified HTTP Response Mocking in Laravel TestsMar 12, 2025 pm 05:09 PM

Laravel provides concise HTTP response simulation syntax, simplifying HTTP interaction testing. This approach significantly reduces code redundancy while making your test simulation more intuitive. The basic implementation provides a variety of response type shortcuts: use Illuminate\Support\Facades\Http; Http::fake([ 'google.com' => 'Hello World', 'github.com' => ['foo' => 'bar'], 'forge.laravel.com' =>

cURL in PHP: How to Use the PHP cURL Extension in REST APIscURL in PHP: How to Use the PHP cURL Extension in REST APIsMar 14, 2025 am 11:42 AM

The PHP Client URL (cURL) extension is a powerful tool for developers, enabling seamless interaction with remote servers and REST APIs. By leveraging libcurl, a well-respected multi-protocol file transfer library, PHP cURL facilitates efficient execution of various network protocols, including HTTP, HTTPS, and FTP. This extension offers granular control over HTTP requests, supports multiple concurrent operations, and provides built-in security features.

12 Best PHP Chat Scripts on CodeCanyon12 Best PHP Chat Scripts on CodeCanyonMar 13, 2025 pm 12:08 PM

Do you want to provide real-time, instant solutions to your customers' most pressing problems? Live chat lets you have real-time conversations with customers and resolve their problems instantly. It allows you to provide faster service to your custom

Announcement of 2025 PHP Situation SurveyAnnouncement of 2025 PHP Situation SurveyMar 03, 2025 pm 04:20 PM

The 2025 PHP Landscape Survey investigates current PHP development trends. It explores framework usage, deployment methods, and challenges, aiming to provide insights for developers and businesses. The survey anticipates growth in modern PHP versio

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment