Backend Development 4 min read

Using PHP header() Function: Syntax, Parameters, and Common Use Cases

This article explains the PHP header() function, covering its syntax, parameter details, and typical scenarios such as page redirection, setting HTTP response headers, status codes, cache control, and file downloads, with clear code examples for each case.

php中文网 Courses
php中文网 Courses
php中文网 Courses
Using PHP header() Function: Syntax, Parameters, and Common Use Cases

In PHP, the header() function is a crucial tool that can perform page redirection and set HTTP response header information. This article provides a detailed introduction to the usage of header() and includes concrete code examples.

Basic Syntax of header()

<code>header(string $header, bool $replace = true, int $http_response_code = 0): bool</code>

$header (required): the HTTP header to send, e.g., "Content-Type: text/html;charset=utf-8".

$replace (optional): whether to replace a previous header of the same name; default is true .

$http_response_code (optional): the HTTP status code to set; must be a valid status code.

Common Scenarios and Code Examples

Implement Page Redirection

The header() function can redirect the user to a specified URL.

<code>header("Location: http://www.example.com");
exit;</code>

Set HTTP Response Headers

It can also set response headers such as Content-Type or Content-Disposition . For example, to set JSON content type:

<code>header("Content-Type: application/json");</code>

Set HTTP Response Status Code

The function can define the HTTP status code, e.g., 200 for success or 404 for not found.

<code>header("HTTP/1.1 404 Not Found");</code>

Prevent Page Caching

To stop browsers from caching a page, set cache‑control headers:

<code>header("Cache-Control: no-cache, no-store, must-revalidate");
header("Pragma: no-cache");
header("Expires: 0");</code>

Set File Download

By setting Content-Disposition to attachment , a file can be offered for download.

<code>header("Content-Disposition: attachment; filename=example.pdf");
header("Content-Type: application/pdf");
header("Content-Length: " . filesize("example.pdf"));
readfile("example.pdf");</code>

The header() function is versatile for both redirection and customizing HTTP headers, and developers should understand its parameters to use it effectively in various backend scenarios.

backendhttpWeb DevelopmentPHPheaderresponse headers
php中文网 Courses
Written by

php中文网 Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.