Php header() function syntax and usage code_PHP tutorial
Syntax:
Void header(string $string[ ,bool $replace=true [, int $http_response_code)
Send the original HTTP header to the client
Note: The
Header function must be called before any actual output, regardless of It is a normal html tag, a blank line in the file, or it comes from php. That is, there cannot be any form of output before this function.
Parameter description:
Parameter Description
string Required. Specifies the header string to be sent.
replace is optional. Indicates whether this header replaces the previous header, or adds a second header.
Default is true (replacement). false (allow multiple headers of the same type).
http_response_code is optional. Forces the HTTP response code to the specified value. (Available in PHP 4 and above)
Common usage examples:
1. Sending server status code
header('HTTP/1.0 404 Not Found');
Common status codes:
Status Code Description
100-199 indicates that the request has been successfully received, and the client is required to continue submitting the next request to complete the entire processing process.
200-299 indicates that the request has been successfully received and the entire processing process has been completed. 200 is commonly used
300-399 The request is not completed. The client needs to further refine the request. For example, the requested resource has been moved to a new address. Commonly used are 302,304
400-499. The client request is incorrect. Commonly used are 404
500- 599 An error occurred on the server side, commonly used 500
For details, please see: HTTP&FTP corresponding prompt information
2. Page jump
// Jump now Redirect
header('Location: http://www.jb51.net/');
// Redirect after 3 seconds
header('refresh:3;url=http:/ /www.jb51.net');
3. Set browser cache
Force the browser not to cache!
[code]
//header('Expires:-1');
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Cache -Control:no-cache,must-revalidate');
header('pragma:no-cache');
header('Last-Modified: '. date('D, j M Y H:i:s T') );
Note:
The time after Expires must be in GMT format, such as: gmdate("M d Y H:i:s");
Cache-control common The values include private, no-cache, max-age, must-revalidate, etc. The default is private. Its function is divided into the following situations according to different re-browsing methods.
Cache-directive Description
public All content will be cached
private content will only be cached in the private cache
no-cache All content will not be cached
no-store All content will be cached Will not be cached in cache or temporary Internet files
must-revalidation/proxy-revalidation If the cached content is invalid, the request must be sent to the server/proxy for revalidation
max-age=xxx (xxx is numeric ) The cached content will expire after xxx seconds. This option is only available in HTTP 1.1, and if used together with Last-Modified, it has a higher priority
Open a new window
If the value of cache-control is specified private, no-cache, must-revalidate, then the server will be accessed again when a new window is opened. And if the max-age value is specified, the server will not be accessed again within this value, such as:
header('cache-control:max-age=5');
Indicates that the server will not be accessed again within 5 seconds after accessing this webpage
Press Enter in the address bar
If the value is private or Must-revalidate, the server will only be accessed the first time, and will not be accessed in the future. If the value is no-cache, it will be accessed every time. If the value is max-age, it will not be accessed again before expiration.
Press the back button
If the value is private, must-revalidate, max-age, it will not be accessed again, and if it is no-cache, it will be accessed again every time
Press the refresh button
Regardless of the value, it will be accessed repeatedly. When the Cache-control value is specified as "no-cache", accessing this page will not leave a page backup in the Internet temporary article folder. In addition, caching can also be affected by specifying the "Expires" value. For example, if you specify the Expires value as a time that has long passed, then if you press Enter repeatedly in the address bar when accessing this website, the access will be repeated every time:
Expires: Fri, 31 Dec 1999 16:00:00 GMT
About "Last-Modified
When the browser requests a URL for the first time, the return status from the server will be 200, the content is the resource you requested, and there is a Last-Modified attribute to mark this file in the service The time when the end of the period was last modified, the format is similar to this:
Last-Modified: Fri, 12 May 2006 18:53:33 GMT
When the client requests this URL for the second time, according to the provisions of the HTTP protocol, the browser The server will send an If-Modified-Since header to the server, asking whether the file has been modified after this time:
If-Modified-Since: Fri, 12 May 2006 18:53:33 GMT
If the server-side resource has not changed, it will automatically return HTTP 304 (Not Changed.) status code with empty content, thus saving the amount of data transferred. When the server-side code changes or the server is restarted, the resource is reissued and the return is similar to the first request. This ensures that resources are not sent to the client repeatedly, and also ensures that when the server changes, the client can get the latest resources.
Last-Modified improves performance
Smart developers will use Last-Modified together with the http header of the ETags request, which can take advantage of the cache of the client (such as the browser). Because the server generates the Last-Modified/Etag tag first, the server can use it later to determine whether the page has been modified. Essentially, the client is asking the server to validate its (client-side) cache by passing this token back to the server.
The process is as follows:
The client requests a page (A)
The server returns page A and adds a Last-Modified to A
The client displays the page and caches the page together with Last-Modified
The client requests page A again and passes the Last-Modified returned by the server in the last request to the server
The server checks the Last-Modified and determines that the page has not been modified since the last client request, and directly Returns a 304 response and an empty response body.
3. File download
For example, download a pdf file
// We'll be outputting a PDF
header('Content-type: application/pdf');
// It will be called downloaded.pdf
//Indicate it It is an attachment, name it and download it
header('Content-Disposition: attachment; filename="downloaded.pdf"');
// The PDF source is in 1.pdf
readfile( '1.pdf');
In fact, you can understand these better this way!
header('content-type:application/octet-sream');
Header('Accept-Ranges:bytes');
//Return by bytes
Header('content-disposition:attachement;filename="filename"');
Header(' Accept-length:'.$filesize);

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

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,

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

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 are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.
