Home Backend Development PHP Tutorial PHP header function usage example

PHP header function usage example

Jul 25, 2016 am 08:57 AM

  1. Header("Location: http://bbs.it-home.org";);
  2. exit; // "exit" must be added after each redirect to avoid After an error occurs, execution continues.
  3. ?>
  4. header("refresh:3;url=http://bbs.it-home.org");
  5. print('Loading, please wait...
    Three seconds Automatically jump after~~~');
  6. Header redirection is equivalent to entering the url in the address bar for the user
  7. ?>
Copy the code

Example 2, prohibit the page from being cached in IE

  1. header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
  2. header('Last-Modified: '.gmdate('D, d M Y H:i: s') .' GMT');
  3. header('Cache-Control: no-store, no-cache, must-ridate');
  4. header('Cache-Control: post-check=0, pre-check=0 ',false);
  5. header('Pragma: no-cache');//Compatible with http1.0 and https
  6. ?>
  7. CacheControl = no-cache
  8. Pragma=no-cache
  9. Expires = -1
Copy Code

Description: If the web pages on the server change frequently, set Expires to -1, indicating immediate expiration. If a web page is updated at 1 am every day, you can set Expires to 1 am the next day. When the HTTP1.1 server specifies CacheControl = no-cache, the browser will not cache the web page. Legacy HTTP 1.0 servers cannot use the Cache-Control header. So for backward compatibility with HTTP 1.0 servers, IE provides special support for HTTP using the Pragma:no-cache header. If the client communicates with the server over a secure connection (https://) and the server returns the Pragma:no-cache header in the response, Internet Explorer does not cache the response.

Note: Pragma:no-cache prevents caching only when used in a secure connection. If used in a non-secure page, the handling is the same as Expires:-1. The page will be cached but marked as expired immediately.

http-equiv meta tag: You can use http-equiv meta to mark the specified http message header in the html page. Older versions of IE may not support html meta tags, so it's best to use http message headers to disable caching.

Example 3: Let the user's browser display a file not found message.

Online information shows: PHP’s function header() can send the Status header to the browser. For example:

  1. header("Status: 404 Not Found")
Copy code

. In fact, the response returned by the browser is:

  1. header("http/1.1 404 Not Found");
Copy code

The first part is the version of the HTTP protocol (HTTP-Version); The second part is the status code (Status); The third part is Reason-Phrase.

Example 4, allowing users to download files (hidden file location) The html tag can be used to download ordinary files. If you want to keep the file confidential and you cannot tell others the file link, you can use the header function to download the file.

  1. header(“Content-type: application/x-gzip”);
  2. header(“Content-Disposition: attachment; filename=filename”);
  3. header(“Content-Description : PHP3 Generated Data”);
  4. ?>
Copy the code

Example 5, enter the content before the header function Generally speaking, HTML content cannot be output before the header function. Similarly, there are setcookie() and session functions. These functions need to add message header information to the output stream.

If there are echo statements before header() is executed, when header() is encountered later, a “Warning: Cannot modify header information – headers already sent by….” error will be reported. There cannot be any text, blank lines, carriage returns, etc. in front of these functions, and it is best to add the exit() function after the header() function.

For example, the following incorrect writing has a blank line between the two php code snippets:

  1. //some code here
  2. ?>
  3. //This should be a blank line
  4. header("http/1.1 403 Forbidden");
  5. exit();
  6. ?>
Copy code

Cause analysis: When a PHP script starts executing, it can send http message header (title) information and body information at the same time. The http message header (from the header() or SetCookie() function) is not sent immediately, instead, it is saved to a list.

In this way, the title information can be modified, including the default title (such as the Content-Type title).

However, once the script sends any non-header output (for example, using HTML or a print() call), then PHP must first send all headers and then terminate the HTTP header. Then continue to send the main data. From this point on, any attempt to add or modify Header information is not allowed, and one of the above error messages will be sent.

Solution: Modify php.ini to turn on caching (output_buffering), or use the caching functions ob_start(), ob_end_flush(), etc. in the program.

Principle analysis: When output_buffering is enabled, PHP does not send HTTP headers when the script sends output.

Instead, it pipes this output into a dynamically growing cache (only available in PHP 4.0, which has a centralized output mechanism).

You can modify/add headers, or set cookies, because headers are not actually sent. When all scripts terminate, PHP will automatically send HTTP headers to the browser, and then send the contents of the output buffer.

Attached are some other examples of php header functions.

  1. // ok
  2. header('HTTP/1.1 200 OK');
  3. //Set a 404 header:
  4. header('HTTP/1.1 404 Not Found');
  5. // Set the address to be permanently redirected
  6. header('HTTP/1.1 301 Moved Permanently');
  7. //Go to a new address
  8. header('Location: http://bbs.it-home.org/');
  9. //File delayed redirection:
  10. header('Refresh: 10; url=http://bbs.it-home.org/');
  11. print 'You will be redirected in 10 seconds';
  12. //Of course, it can also Implemented using html syntax
  13. //
  14. // override X-Powered-By: PHP:
  15. header('X-Powered-By: PHP/4.4.0′);
  16. header('X-Powered-By: Brain/0.6b');
  17. //Document language
  18. header('Content-language: en') ;
  19. //Tell the browser the last modification time
  20. $time = time() – 60; // or filemtime($fn), etc
  21. header('Last-Modified: '.gmdate('D, d M Y H:i :s', $time).' GMT');
  22. //Tell the browser that the document content has not changed
  23. header('HTTP/1.1 304 Not Modified');
  24. //Set the content length
  25. header('Content-Length : 1234′);
  26. //Set as a download type
  27. header('Content-Type: application/octet-stream');
  28. header('Content-Disposition: attachment; filename="example.zip"');
  29. header('Content-Transfer-Encoding: binary');
  30. // load the file to send:
  31. readfile('example.zip');
  32. // disable caching for the current document
  33. header('Cache-Control: no- cache, no-store, max-age=0, must-ridate');
  34. header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
  35. header('Pragma: no-cache');
  36. //Set content type:
  37. header('Content-Type: text/html; charset=iso-8859-1′);
  38. header('Content-Type: text/html; charset=utf -8′);
  39. header('Content-Type: text/plain'); //Plain text format
  40. header('Content-Type: image/jpeg'); //JPG image
  41. header('Content-Type: application/zip'); // ZIP file
  42. header('Content-Type: application/pdf'); // PDF file
  43. header('Content-Type: audio/mpeg'); // Audio file
  44. header(' Content-Type: application/x-shockwave-flash'); //Flash animation
  45. //Display login dialog box
  46. header('HTTP/1.1 401 Unauthorized');
  47. header('WWW-Authenticate: Basic realm=”Top Secret"');
  48. print 'Text that will be displayed if the user hits cancel or ';
  49. print 'enters wrong login data';
  50. ?>
Copy code


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,

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.

How to debug CLI mode in PHPStorm? How to debug CLI mode in PHPStorm? Apr 01, 2025 pm 02:57 PM

How to debug CLI mode in PHPStorm? When developing with PHPStorm, sometimes we need to debug PHP in command line interface (CLI) mode...

How to automatically set permissions of unixsocket after system restart? How to automatically set permissions of unixsocket after system restart? Mar 31, 2025 pm 11:54 PM

How to automatically set the permissions of unixsocket after the system restarts. Every time the system restarts, we need to execute the following command to modify the permissions of unixsocket: sudo...

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.

How to send a POST request containing JSON data using PHP's cURL library? How to send a POST request containing JSON data using PHP's cURL library? Apr 01, 2025 pm 03:12 PM

Sending JSON data using PHP's cURL library In PHP development, it is often necessary to interact with external APIs. One of the common ways is to use cURL library to send POST�...

See all articles