PHP header() Function Tutorial

HTTP protocol uses the HTTP headers in order to provide information to the user browser. HTTP headers may provide information like content type, response code, timezone information, caching, etc. HTTP header is created by the web server and as a dynamic web programming language PHP provides header() function in order to add, change the HTTP header. header() function is mainly used to send raw HTTP headers. PHP header() function is available after PHP version 4.0 and later. Raw HTTP header means cleartext header information.

How does HTTP Header work?

Before starting to provide examples of the PHP header function we need to provide the HTTP Header work logic. HTTP is a stateless protocol and every request is atomic. HTTP requests and responses contain header information in order to set some information and attributes. Below you can see an HTTP response which first part is the header.

HTTP/1.x 200 OK
Transfer-Encoding: chunked
Date: Sat, 20 Nov 2019 04:36:25 GMT
Server: Nginx
Connection: close
X-Powered-By: W3 Total Cache/0.8
Pragma: public
Expires: Sat, 28 Nov 2019 05:36:25 GMT
Etag: "asdfasrtv;gz"
Cache-Control: max-age=3600, public
Content-Type: text/html; charset=UTF-8
Last-Modified: Sat, 20 Nov 2019 03:50:37 GMT
Content-Encoding: gzip
Vary: Accept-Encoding, Cookie, User-Agent
 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Wisetut.com Tutorials</title>
<!-- ... rest of the html ... -->

header() Function Syntax

PHP provides the header() function in order to add or change attributes to the HTTP header. header() function accepts 3 parameters where only one parameter is must and other two are optional.

header ( string $header , bool $replace = TRUE , int $http_response_code )

$header parameter is used to provide the header content we want to add. This parameter will contain the complete HTTP header line like Server: Nginx . The $header parameter is must and should be provided every time the header() function is used. This parameter should be in string format.

$replace parameter is used to specify whether the already existing parameter should be replaced with the provided $header parameter. $replace parameter is optional and if not provided the default value is TRUE which means the existing HTTP header will be replaced with the provided one.

$http_response_code parameter is used to provide the HTTP response or status codefor the response. This parameter is also optional. The $http_response_code type is integer.

header() Function Use Cases

PHP header() function provides the ability to change or alter the HTTP header. As HTTP provides a lot of different header attributes you can use header() function to use this header for different use cases. Below you can find some popular use cases for the PHP header() function.

  • Redirect To New URL
  • Set Content Type
  • Set Content Length
  • Set Content Language
  • Set HTTP Status/Response Code
  • Set Timezone
  • Provide Technology and Web Server Information
  • Disable Caching
  • HTTP Basic Authentication

Redirect To New URL/Location with header() Function

The most popular use case of the header() function is redirecting to the new location or URL. URL or URI is the address identifier or simply address of the web page like https://wisetut.com/ and HTTP Location header is used to redirect users to another URL which can be the same or different domain. In the following example, we will redirect the user to the https://www.poftut.com/ by using the Location header. You can provide the header string in single or double-quotes.

<?php
   header('Location: https://www.poftut.com/');
?>

As a special case, the Location header will also set the HTTP response or status code as 302 REDIRECT automatically unless another status code set previously. Keep in mind that after providing the Location header do not put any PHP code because none of them will be executed as the response only contains a redirect.

Even 302 REDIRECT is popular for redirecting users to the new URL there are other redirect status codes and types like below. All of the set different reasons for the redirect. Even these reasons do not have meaning for humans they can be meaningful for bots, SEO, Search Engine, applications, and services.

<?php
   // HTTP Status 301 Moved Permanently
   header("Location: /my-new-url.php",TRUE,301);

   // HTTP Status 303 See Other
   header("Location: /my-new-url.php",TRUE,303);

   // HTTP Status 307 Temporary Redirect
   header("Location: /my-new-url.php",TRUE,307);
?>

As stated previously after providing the Location header no HTTP data or content can be sent to the user. If you want to provide some HTTP data or content in order to provide information like “You will be redirected in 5 seconds” you should use the Refresh header like below. Refresh header will refresh the web page into specified URL after specified time.

<?php
   header('Refresh: 5; url=https://www.wisetut.org/');
   print 'You will be automatically redirected to the WiseTut in 5 seconds';
?>

Set Content Type with header() Function

HTTP protocol generally provides web pages and contents like HTML code, JavaScript code, CSS, images, fonts, etc. But Files, Videos can be also provided via HTTP. Different types of content can be provided with the Content-Type HTTP header. The Content-Type header provides HTTP response data type. For example in the following example a PDF or Portable Document Formatted file data will be provided a response.

<?php
   // Set the Content-Type HTTP header as PDF
   header('Content-Type: application/pdf');

   // Set the file name of the PDF file
   header('Content-Disposition: attachment;            filename="Wisetut.pdf"');

   // Specify the PDf file location in order to read data and return as HTTP response
   readfile('Wise.pdf');
?>

Following Content-Type’s can be used for different file or data formats.

<?php
   // Set the Content-Type HTTP header as Amazon Kindle eBook format
   header('Content-Type: application/vnd.amazon.ebook');

   // Set the Content-Type HTTP header as Cascading Style Sheets (CSS)
   header('Content-Type: text/css');

   // Set the Content-Type HTTP header as Microsoft Word
   header('Content-Type: application/msword');

   // Set the Content-Type HTTP header as Graphics Interchange Format (GIF)
   header('Content-Type: image/gif');

   // Set the Content-Type HTTP header as HyperText Markup Language (HTML)
   header('Content-Type: text/javascript');

   // Set the Content-Type HTTP header as JavaScript
   header('Content-Type: text/html');

   // Set the Content-Type HTTP header as Portable Network Graphics (PNG)
   header('Content-Type: image/png');

   // Set the Content-Type HTTP header as WEBP image
   header('Content-Type: image/webp');
?>

Set HTTP Status/Response Code with header() Function

HTTP status code is used to provide the HTTP response status like 200 Success, 404 Not Found, etc. header() function can provide the HTTP status code in different ways. First we can set the header string with a valid status code like below. In the following example we will return 404 Not Found.

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

An alternative way is to provide the status code with the $http_response_code parameter. We will also provide the $header parameter for an HTTP header.

<?php
   header("Server: Nginx", TRUE, 404);
?>

Set X-Powered-By Value with header() Function

X-Powered-By HTTP header is used to provide some information about the webserver, technology, application, programming language, etc. It is simply a trademark about the server-side. You can provide the X-Powered-By header by using the PHP header() function.

<?php
   header("X-Powered-By: PHP/25.0");
 
   header("X-Powered-By: WiseTut");

   header("X-Powered-By: ZendServer 8.5.0");

   header("X-Powered-By: ASP.NET");

   header("X-Powered-By: IIS 8.0");
?>

Content Language with header() Function

We live in a multi-language world and web. A web page can be created in different languages and current language can be provided to the user via Content-Language HTTP response header.

<?php

   // Set Content Language As German
   header("Content-Language: de-De");

   // Set Content Language As English
   header("Content-Language: en-UK");

   // Set Content Language As Turkish
   header("Content-Language: tr-TR");

   // Set Content Language As American English
   header("Content-Language: en-US");

   // Set Content Language As Spanish
   header("Content-Language: sp-SP");
 
?>

Disable Caching with header() Function

PHP is a dynamic server-side programming language where PHP web applications and sites generally create dynamic content that is regularly changing. The HTTP protocol provides a caching mechanism in order to preserve bandwidth, time, and increases the performance of the web site or web page navigation. Using HTTP cache will prevent the changes to be provided to the user and the header() function can be used to disable caching with the Cache-Control HTTP header. In the following example, we will disable the cache for the current response and set date in the past to expire. We will set no-cache and must-revalidate values to the Cache-Control header.

<?php
   header("Cache-Control: no-cache, must-revalidate"); 
   header("Expires: Sun, 16 Jan 2020 05:00:00 GMT"); 
?>

HTTP Basic Authentication with header() Function

HTTP Basic Authentication provides the user to authenticate itself using the HTTP. As its name suggests it is a basic level authentication with a username and password. HTTP Basic Authentication can be enabled with the WWW-Authenticate header. PHP header() function can be used to enable the HTTP Basic authentication. In the following example, we will enable the HTTP Basic authentication with the NTLM hashing. We will also provide the $replace parameter as the FALSE parameter in order to prevent to override previous header value. We will use the WWW-Authenticate two times to enable authentication and set hashing as NTLM.

<?php
   header("WWW-Authenticate: Negotiate");
   header("WWW-Authenticate: NTLM", false);
?>

PHP Cannot Modify Header Error

Normally HTTP response headers are generated by the web server software like Apache, Nginx, IIS, etc. Modifying or Changing HTTP response headers with PHP is a useful method but may create problems, exceptions, and errors.

PHP Cannot Modify Header Information Error is common while using the header() function. The cause of this error is running the header() function before creating an HTML output. Look following incorrect header() function usage examples.

<?php
   echo "How Are You";
   header ('Location: https://wisetut.com/');
?>
How Are You! <?php
header ('Location: https://wisetut.com/');
?>

The correct usage of the header() function is running the PHP statement before using the header() function. We can connect the database or create a variable or anything else with the PHP which will create the HTML output and then use the header() function like below.

<?php

   mysql_query("SELECT * FROM USERS");

   $test= "wisetut";

   header ('Location: https://wisetut.com/');

?>

Leave a Comment