Home Backend Development PHP Tutorial PHP Hander详解【转】

PHP Hander详解【转】

Jun 23, 2016 pm 02:31 PM

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);?>
Copy after login

 

 

注: 即使启用了 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 部分中去。

Statement of this Website
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

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

What are Enumerations (Enums) in PHP 8.1? What are Enumerations (Enums) in PHP 8.1? Apr 03, 2025 am 12:05 AM

The enumeration function in PHP8.1 enhances the clarity and type safety of the code by defining named constants. 1) Enumerations can be integers, strings or objects, improving code readability and type safety. 2) Enumeration is based on class and supports object-oriented features such as traversal and reflection. 3) Enumeration can be used for comparison and assignment to ensure type safety. 4) Enumeration supports adding methods to implement complex logic. 5) Strict type checking and error handling can avoid common errors. 6) Enumeration reduces magic value and improves maintainability, but pay attention to performance optimization.

How does session hijacking work and how can you mitigate it in PHP? How does session hijacking work and how can you mitigate it in PHP? Apr 06, 2025 am 12:02 AM

Session hijacking can be achieved through the following steps: 1. Obtain the session ID, 2. Use the session ID, 3. Keep the session active. The methods to prevent session hijacking in PHP include: 1. Use the session_regenerate_id() function to regenerate the session ID, 2. Store session data through the database, 3. Ensure that all session data is transmitted through HTTPS.

Describe the SOLID principles and how they apply to PHP development. Describe the SOLID principles and how they apply to PHP development. Apr 03, 2025 am 12:04 AM

The application of SOLID principle in PHP development includes: 1. Single responsibility principle (SRP): Each class is responsible for only one function. 2. Open and close principle (OCP): Changes are achieved through extension rather than modification. 3. Lisch's Substitution Principle (LSP): Subclasses can replace base classes without affecting program accuracy. 4. Interface isolation principle (ISP): Use fine-grained interfaces to avoid dependencies and unused methods. 5. Dependency inversion principle (DIP): High and low-level modules rely on abstraction and are implemented through dependency injection.

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What is REST API design principles? What is REST API design principles? Apr 04, 2025 am 12:01 AM

RESTAPI design principles include resource definition, URI design, HTTP method usage, status code usage, version control, and HATEOAS. 1. Resources should be represented by nouns and maintained at a hierarchy. 2. HTTP methods should conform to their semantics, such as GET is used to obtain resources. 3. The status code should be used correctly, such as 404 means that the resource does not exist. 4. Version control can be implemented through URI or header. 5. HATEOAS boots client operations through links in response.

How do you handle exceptions effectively in PHP (try, catch, finally, throw)? How do you handle exceptions effectively in PHP (try, catch, finally, throw)? Apr 05, 2025 am 12:03 AM

In PHP, exception handling is achieved through the try, catch, finally, and throw keywords. 1) The try block surrounds the code that may throw exceptions; 2) The catch block handles exceptions; 3) Finally block ensures that the code is always executed; 4) throw is used to manually throw exceptions. These mechanisms help improve the robustness and maintainability of your code.

What are anonymous classes in PHP and when might you use them? What are anonymous classes in PHP and when might you use them? Apr 04, 2025 am 12:02 AM

The main function of anonymous classes in PHP is to create one-time objects. 1. Anonymous classes allow classes without names to be directly defined in the code, which is suitable for temporary requirements. 2. They can inherit classes or implement interfaces to increase flexibility. 3. Pay attention to performance and code readability when using it, and avoid repeatedly defining the same anonymous classes.

See all articles