The Entire Concept of Header in PHP in Detail

PHP stands for Hypertext Preprocessor and is a server-side programming language that was created with web development in mind. It is open-source, which means you can download and use it for free. It's incredibly easy to pick up and use. The files contain the “.php” extension.

Rasmus Lerdorf was the driving force behind the first version of PHP, as well as a contributor to succeeding versions. It is an interpreted language that does not necessitate the use of a compiler.

Many databases, including Oracle, Microsoft SQL Server, MySQL, PostgreSQL, Sybase, and Informix, can be combined with it.

It is used to regulate user access and hold a content management system like WordPress.

Example

<html>

<head>

<title>PHP Example</title>

</head>

<body>

<?php echo "Hello, World! This is PHP code";?>

</body>

</html>

Output

/Header_In_PHP_1

Stand Out From Your Peers this Appraisal Season

Start Learning With Our FREE CoursesEnroll Now
Stand Out From Your Peers this Appraisal Season

What Is a Header in PHP? Explain With Syntax

The header in PHP is a PHP built-in function for sending a raw HTTP header. The HTTP functions are those that manipulate information sent by the webserver to the client or browser before it sends any further output. The header() function in PHP sends a raw HTTP header to a client or browser. Before HTML, XML, JSON, or other output is given to a browser or client, the server sends raw data as header information with the request (particularly HTTP Request). Headers in PHP contain additional details about the object delivered in the message body, as well as the request and response.

Syntax

void header( $header, $replace = TRUE, $http_response_code )

It includes a header string in the string. There are two types of header calls in general. One is a header that begins with the string "HTTP/" and is used to determine the HTTP status code to send. Another is the "Location," which is required.

  • replace: This is an optional parameter that specifies whether the header should add a new header or replace the previous one.
  • http response code is an optional parameter that sets the HTTP response code to a specific value (available in PHP 4.3 and higher).

The header() method is a built-in function that allows you to deliver a raw HTTP header to a client. HTTP functions allow you to manipulate data supplied to the browser by the webserver before it sends any additional output. You must call it before any actual output is sent, whether from HTML tags, blank lines in a file, or a PHP file.

Example

<pre>

<?php

header("Expires: Sun, 22 Jun 1997 04:00:00 GMT");

header("Cache-Control: no-cache, must-revalidate");

header("Pragma: no-cache");

print_r(headers_list());

?>

</pre>

Output

Header_In_PHP_2

Example

<?php

// Test image.

$t1 = 'https://cdn.educba.com/test/image.png';

// Headers being sent by the client

$headers = apache_request_headers();

// To check if the cache is being validated by the client and whether it is current

if (isset($headers['If-Modified-Since']) && (strtotime($headers['If-Modified-Since']) == ftime($t1))) {

// We shall respond with '304 Not Modified' if the client cache is current

header('Last-Modified: '.gmdate('D, d M Y H:i:s', ftime($t1)).' GMT', true, 304);

echo(‘’);

} else {

// We shall display '200 OK' by outputting the image if it is not cached or outdated cache

header('Last-Modified: '.gmdate('D, d M Y H:i:s', ftime($t1)).' GMT', true, 200);

header('Content-Length: '.filesize($t1));

header('Content-Type: image/png');

print file_get_contents($t1);

}

?>

Output

Header_In_PHP_3.

Parameter Values of the Header Function Along With the Use

This function accepts the following three parameters, as noted above and described below:

  • $header: The header in the PHP string is stored in this argument. Header calls can be divided into two categories. The first header begins with the string "HTTP/," which is used to determine which HTTP status code should be sent. 
  • The “Location”: It is the second type of header. It is a required parameter.
  • $replacement: It is a parameter that can be turned off. It shows whether the header should replace or add a second header. True is the default value (will replace). If $replace is False, it forces additional headers of the same kind.
  • $http response code: It's a non-mandatory parameter. It sets the HTTP response code to the value supplied (PHP 4.3 and above).

Example 

<?php

// PHP program to describes header in PHP

// Set a past date

header("Expires: Sun, 25 Jul 1997 06:02:34 GMT");

header("Cache-Control: no-cache");

header("Pragma: no-cache");

?>

<html>

<body>

<p>Hello World!</p>

<!-- PHP program to display

header list -->

<?php

print_r(headers_list());

?>

</body>

</html>

Output

Header_In_PHP_4

Full Stack Web Developer Course

To become an expert in MEAN StackView Course
Full Stack Web Developer Course

How to Download Files Using a Header in PHP

To download photos, zip files, pdf documents, exe files, and other types of files, you usually don't need to use a server-side scripting language like PHP. If you store such a file in a publicly accessible folder, you can simply build a hyperlink linking to it, and the browser will instantly download the file anytime a user clicks on the link.

Using the header in the PHP readfile() method, you can force images or other types of data to download straight to the user's hard drive. Now, make a simple image gallery here, that lets people download picture files from the browser with a single mouse click. Create a file called "image-gallery.php" and paste the code below into it.

<?php

// what kind of document to be downloaded

header('Content-Type: application/pdf');

// name the file as document.pdf

header('Content-Disposition: attachment; filename="document.pdf"');

// Read original.pdf file and output it

readfile('original.pdf');

To download any file during runtime, there are three essential stages, they are:

  • Define the type of file to be downloaded
  • Give it a name
  • Read the file's/content texts

These are the three basic processes for downloading files on the fly, in addition to numerous intermediate processes in the header in PHP.

How to Prevent Page Caching Using Headers in PHP?

Header in PHP is well-known for its ability to handle dynamic data. However, there are times when you don't want the data to be cached by the client browser (to load the website faster of course). You can override this condition by using the header() function and adding certain options that prevent web pages from being cached.

Header_In_PHP_5

This article introduced cache-control: no-cache to ensure that the server sends current data rather than cached data each time a browser requests a specific URL. There is also an expires option to the past date, which indicates that the web page has already expired and that new data from the client browser is awaited.

Example

<?php

header("Cache-Control: no-cache, hence should-revalidate");

header("Expires: Sun, 25 Jun 1999 04:00:00 GMT");

// Providing some random date in the past

echo('Displaying header information: Cache-Control: no-cache, hence should-revalidate' );

?>

Output

Header_In_PHP_6

Example

<?php

// PHP program to describes header function

// Set a past date

header("Expires: Sun, 25 Jul 1997 06:02:34 GMT");

header("Cache-Control: no-cache");

header("Pragma: no-cache");

?>

<html>

<body>

<p>Hello World!</p>

<!-- PHP program to display

header list -->

<?php

print_r(headers_list());

?>

</body>

</html>

Output

Header_In_PHP_7.

Advance your career as a MEAN stack developer with the Full Stack Web Developer - MEAN Stack Master's Program. Enroll now!

Conclusion 

The header function, which was first introduced in PHP 4, plays a vital role in development. This function was often utilized in the core of current frameworks to redirect users to a certain function. One of the key features of the header in the PHP method is the ability to download files at runtime and configure cache control.

Hope you have understood everything there is to know about the header() function in PHP and its applications. For more information on this topic, you can join the Simplilearn's Full Stack Web Development course and get the clarity you need. Our skill-up course also offers you the right understanding to get you placed in the best positions.

Have any questions for us? Leave them in the comments section of this article. Our experts will get back to you on the same, as soon as possible!

About the Author

SimplilearnSimplilearn

Simplilearn is one of the world’s leading providers of online training for Digital Marketing, Cloud Computing, Project Management, Data Science, IT, Software Development, and many other emerging technologies.

View More
  • Disclaimer
  • PMP, PMI, PMBOK, CAPM, PgMP, PfMP, ACP, PBA, RMP, SP, and OPM3 are registered marks of the Project Management Institute, Inc.