search
HomeBackend DevelopmentPHP TutorialDetailed description of PHP header() function (301, 404 and other error settings)_PHP tutorial

If you have just started learning PHP, there may be many functions that need to be studied. Today we will learn how to use PHP Header(). For more instructions, please refer to the PHP Chinese manual. The following is about Detailed instructions for using header function

No matter how many headers the page has, it will execute the last one, but it is conditional, for example:

header('Location:http://www.bkjia.com');
header('Location:http://www.g.cn');
header('Location:http: //www.baidu.com');

This will jump to Baidu

header('Location:http://www.bkjia.com');echo 'Bangkezhijia;
header('Location:http://www.g.cn');
header('Location:http://www.baidu.com');

This will jump to Google
The following are detailed instructions for using the header function
1. Function:
~~~~~~~~~
PHP only converts HTML using the HTTP protocol The header of the document is sent to the browser, telling the browser how to process this page. As for the transmitted content, you need to be familiar with the HTTP protocol, which has nothing to do with PHP
The traditional header must contain one of the following three headers , and can only appear once.

Location: xxxx:yyyy/zzzz
Content-Type: xxxx/yyyy
Status: nnn xxxxxx

2. First, let’s understand how the HTTP protocol operates
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~
The HTTP protocol is based on the request/response paradigm. After a client establishes a connection with the server, it sends a request to the server. The format of the request is a uniform resource identifier, a protocol version number, followed by MIME information including request modifiers, client information and possible content. After receiving the request, the server gives corresponding response information. The format is a status line including the protocol version number of the information, a success or error code, followed by MIME information including server information, entity information and possible content.
It is divided into four processes. In the HTTP protocol, the server refers to the part that provides HTTP services, and the client refers to the browser or download tool you use, etc. During communication, the client sends a request for connection, and the server establishes the connection; then, the client sends an HTTP request (Request), and the server returns response information (Respond), thereby completing an HTTP operation.

HTTP status detection (HTTP Header): http://www.bkjia.com/tools/http_header.php

3. The meaning of HTTP protocol status code
~~~~~~~~~~~~~~~~~~~~~~~~~~~~

1×× Reserved
2×× Indicates that the request was successfully received
3×× To complete the request, the customer needs to further refine the request
4×× Customer error
5×× Server error

4. Operation examples:
~~~~~~~~~~~~~
Redirect function, this is the most common

Header("Location: http://www.bkjia.com/");
?>

Force users to access this every time Get the latest data when the page is running, rather than using the client's cache.

Code
//Tell the browser the expiration time of this page (expressed in Greenwich Mean Time), as long as it is a date that has already passed.
header("Expires: Mon, 26 Jul 1970 05:00:00 GMT");
//Tell the browser the last updated date of this page (expressed in Greenwich Mean Time), which is the current day. The purpose is Force the browser to obtain the latest information
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . "GMT");
//Tell the client browser not to use cache
header("Cache-Control: no-cache, must-revalidate");
//Parameters (compatible with previous servers), that is, compatible with HTTP1.0 protocol
header("Pragma: no- cache");
//Output MIME type
header("Content-type: application/file");
//File length
header("Content-Length: 227685");
//Accepted range units
header("Accept-Ranges: bytes");
//The default file name in the file save dialog box
header("Content-Disposition: attachment; filename=$filename");
?>

Output the status value to the browser, mainly used for access control

header('HTTP/1.1 401 Unauthorized');
header('status: 401 Unauthorized');
?>

For example, if you want to restrict a user from accessing this page, you can set the status to 404, as shown below, so that the browser will display that the page does not exist

header('HTTP/1.1 404 Not Found');
header("status: 404 Not Found");
?>

Note: Traditional headers must contain one of the following three headers and can only appear once. Content-Type: xxxx/yyyy Location: xxxx:yyyy/zzzz Status: nnn xxxxxx can appear more than twice in the new multipart header specification (Multipart MIME).
Usage Example
Example 1: This example redirects the browser to the official website of PHP.

Header("Location: http://www.bkjia.com/"); exit;

Example 2: If you want the user to get the latest data every time, instead of the data in the Proxy or cache, you can use the following header

header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . "GMT "); header("Cache-Control: no-cache, must-revalidate");
header("Pragma: no-cache");

Example 3: Let the user's browser display a message that the file cannot be found.

header("Status: 404 Not Found");

Example 4: Allow users to download files.

header("Content-type: application/x-gzip");
header("Content-Disposition: attachment; filename=filename");
header("Content-Description: PHP3 Generated Data ");

header -- Send a raw HTTP header description

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

The header() function is used to send a raw HTTP header. See the HTTP/1.1 specification for more information on HTTP headers.
 The optional parameter replace indicates whether to replace the previous similar header or add a header of the same type. The default is replacement, but setting it to FALSE can force multiple headers of the same type to be sent. For example:

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

The second optional parameter http_response_code forces the HTTP response code to the specified value (this parameter is new in PHP 4.3.0).
There are two special header calls. The first is a header that begins with the string "HTTP/" (case does not matter), which can be used to determine the HTTP status code to be sent. For example, if you configure Apache to use PHP to handle error-handling requests for file not found (using the ErrorDocument directive), you need to ensure that the script generates the correct status code.

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

Note: The HTTP status code header line is always the first one sent to the client, regardless of whether the actual header() call is the first one. Unless HTTP headers have already been sent, they can be overwritten at any time by calling the header() function with a new status line.

 HTTP status detection (HTTP Header): http://www.bkjia.com/tools/http_header.php

The second special case is the "Location:" header. It doesn't just send this header back to the browser, it also returns a REDIRECT (302) status code to the browser, unless a 3xx status code has been issued previously.

  header("Location: http://www.example.com/"); /* Redirect the browser*/
 /* Make sure that after redirection, the subsequent code will not Executed*/
exit;
?>

Note: The HTTP/1.1 standard requires an absolute address URI as the parameter of Location:, but some clients support relative URIs. You can usually use the $_SERVER['HTTP_HOST'], $_SERVER['PHP_SELF'] and dirname() functions to generate absolute URIs from relative URIs yourself:

  header("Location: http://%22.$_server['http_host'/]
 . rtrim(dirname($_SERVER['PHP_SELF']), '/\ ')
 ."/".$relative_url);
 ?>

Note: Even if session.use_trans_sid is enabled, the Session ID will not be passed along with the Location header information. Must be passed manually as SID constant.
 
  PHP scripts usually generate some dynamic content, which must not be cached by browsers or proxy servers. Many proxy servers and browsers can disable caching by:

GMT"); // Past time
 ?>

Note: You may find that even if you do not output all the above codes, the web page is not buffered. There are many options that users can set to change the browser's default caching behavior. By sending the above headers, it should be possible to override any settings that could cause script pages to be cached.

 

In addition, when session is used, the session_cache_limiter() function and the session.cache_limiter option can be used to automatically generate the correct cache-related headers.

Remember that header() must be called before any actual output, whether from regular HTML markup, blank lines or PHP. A common mistake is that when reading code through include(), require() or some other file access function, some spaces or empty lines are sent before calling header(). This error is also common in a single PHP/HTML file.

 
  /* This will generate an error because something has been output before calling header()
 */
 header('Location: http://www.example.com/');
 ?>

Note: Since PHP 4, this problem can be solved through some output buffering functions. The cost is that all output to the browser is cached on the server until a command is issued to send it. You can use ob_start() and ob_end_flush() in the code to achieve this function, or by modifying the output_buffering configuration option in php.ini, or by modifying the server configuration file.

Attached are two common uses of header():

//Set the page encoding:
header('Content-Type:text/html;charset=gb2312');
//Adjust the page:
header('location:http://www .baidu.com');

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/363871.htmlTechArticleIf you have just started learning PHP, there may be many functions to study. Today we will learn about PHP Header() How to use, for more instructions, please refer to the PHP Chinese manual,...
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
How can you prevent session fixation attacks?How can you prevent session fixation attacks?Apr 28, 2025 am 12:25 AM

Effective methods to prevent session fixed attacks include: 1. Regenerate the session ID after the user logs in; 2. Use a secure session ID generation algorithm; 3. Implement the session timeout mechanism; 4. Encrypt session data using HTTPS. These measures can ensure that the application is indestructible when facing session fixed attacks.

How do you implement sessionless authentication?How do you implement sessionless authentication?Apr 28, 2025 am 12:24 AM

Implementing session-free authentication can be achieved by using JSONWebTokens (JWT), a token-based authentication system where all necessary information is stored in the token without server-side session storage. 1) Use JWT to generate and verify tokens, 2) Ensure that HTTPS is used to prevent tokens from being intercepted, 3) Securely store tokens on the client side, 4) Verify tokens on the server side to prevent tampering, 5) Implement token revocation mechanisms, such as using short-term access tokens and long-term refresh tokens.

What are some common security risks associated with PHP sessions?What are some common security risks associated with PHP sessions?Apr 28, 2025 am 12:24 AM

The security risks of PHP sessions mainly include session hijacking, session fixation, session prediction and session poisoning. 1. Session hijacking can be prevented by using HTTPS and protecting cookies. 2. Session fixation can be avoided by regenerating the session ID before the user logs in. 3. Session prediction needs to ensure the randomness and unpredictability of session IDs. 4. Session poisoning can be prevented by verifying and filtering session data.

How do you destroy a PHP session?How do you destroy a PHP session?Apr 28, 2025 am 12:16 AM

To destroy a PHP session, you need to start the session first, then clear the data and destroy the session file. 1. Use session_start() to start the session. 2. Use session_unset() to clear the session data. 3. Finally, use session_destroy() to destroy the session file to ensure data security and resource release.

How can you change the default session save path in PHP?How can you change the default session save path in PHP?Apr 28, 2025 am 12:12 AM

How to change the default session saving path of PHP? It can be achieved through the following steps: use session_save_path('/var/www/sessions');session_start(); in PHP scripts to set the session saving path. Set session.save_path="/var/www/sessions" in the php.ini file to change the session saving path globally. Use Memcached or Redis to store session data, such as ini_set('session.save_handler','memcached'); ini_set(

How do you modify data stored in a PHP session?How do you modify data stored in a PHP session?Apr 27, 2025 am 12:23 AM

TomodifydatainaPHPsession,startthesessionwithsession_start(),thenuse$_SESSIONtoset,modify,orremovevariables.1)Startthesession.2)Setormodifysessionvariablesusing$_SESSION.3)Removevariableswithunset().4)Clearallvariableswithsession_unset().5)Destroythe

Give an example of storing an array in a PHP session.Give an example of storing an array in a PHP session.Apr 27, 2025 am 12:20 AM

Arrays can be stored in PHP sessions. 1. Start the session and use session_start(). 2. Create an array and store it in $_SESSION. 3. Retrieve the array through $_SESSION. 4. Optimize session data to improve performance.

How does garbage collection work for PHP sessions?How does garbage collection work for PHP sessions?Apr 27, 2025 am 12:19 AM

PHP session garbage collection is triggered through a probability mechanism to clean up expired session data. 1) Set the trigger probability and session life cycle in the configuration file; 2) You can use cron tasks to optimize high-load applications; 3) You need to balance the garbage collection frequency and performance to avoid data loss.

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

Video Face Swap

Video Face Swap

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

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

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.

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function