Whether you're a programmer or not, you have seen it everywhere on the web. Even your first Hello World PHP script sent HTTP headers without you realizing it. In this article, we are going to learn about the basics of HTTP headers and how we can use them in our web applications.

HTTP stands for "Hypertext Transfer Protocol". The entire World Wide Web uses this protocol. It was established in the early 1990s. Almost everything you see in your browser is transmitted to your computer over HTTP. For example, when you opened this article page, your browser probably sent over 40 HTTP requests and received HTTP responses for each.

HTTP headers are the core part of these HTTP requests and responses, and they carry information about the client browser, the requested page, the server, and more.

### Example

When you type a URL in your address bar, your browser sends an HTTP request, and it may look like this:

 1 GET /tutorials/other/top-20-mysql-best-practices/ HTTP/1.1  2 Host: code.tutsplus.com  3 User-Agent: Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.1.5) Gecko/20091102 Firefox/3.5.5 (.NET CLR 3.5.30729)  4 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8  5 Accept-Language: en-us,en;q=0.5  6 Accept-Encoding: gzip,deflate  7 Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7  8 Keep-Alive: 300  9 Connection: keep-alive  10 Cookie: PHPSESSID=r2t5uvjq435r4q7ib3vtdjq120  11 Pragma: no-cache  12 Cache-Control: no-cache 

The first line is the "Request Line", which contains some basic information on the request. And the rest are the HTTP headers.

After that request, your browser receives an HTTP response that may look like this:

 1 HTTP/1.x 200 OK  2 Transfer-Encoding: chunked  3 Date: Sat, 28 Nov 2009 04:36:25 GMT  4 Server: LiteSpeed  5 Connection: close  6 X-Powered-By: W3 Total Cache/0.8  7 Pragma: public  8 Expires: Sat, 28 Nov 2009 05:36:25 GMT  9 Etag: "pub1259380237;gz"  10 Cache-Control: max-age=3600, public  11 Content-Type: text/html; charset=UTF-8  12 Last-Modified: Sat, 28 Nov 2009 03:50:37 GMT  13 X-Pingback: https://code.tutsplus.com/xmlrpc.php  14 Content-Encoding: gzip  15 Vary: Accept-Encoding, Cookie, User-Agent  16 17   18   19   20   21 Top 20+ MySQL Best Practices - Nettuts+  22  

The first line is the "Status Line", followed by "HTTP Headers", until the blank line. After that, the "content" starts (in this case, the HTML output).

When you look at the source code of a web page in your browser, you will only see the HTML portion and not the HTTP headers, even though they actually have been transmitted together, as you can see above.

These HTTP requests are also sent and received for other things, such as images, CSS files, JavaScript files, etc. That's why I said earlier that your browser sent at least 40 or more HTTP requests as you loaded just this article page.

Now, let's start reviewing the structure in more detail.

### How to See HTTP Headers

I used Firefox Firebug to analyze HTTP headers, but you can use the Developer Tools in Firefox, Chrome, or any modern web browser to view HTTP headers.

In PHP:

#### Host

An HTTP request is sent to a specific IP address. But since most servers are capable of hosting multiple websites under the same IP, they must know which domain name the browser is looking for.

 1 Host: code.tutsplus.com 

This is basically the host name, including the domain and the subdomain.

In PHP, it can be found as $_SERVER['HTTP_HOST'] or $_SERVER['SERVER_NAME'].

#### User-Agent

 1 User-Agent: Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.1.5) Gecko/20091102 Firefox/3.5.5 (.NET CLR 3.5.30729) 

This header can carry several pieces of information, such as:

• browser name and version
• operating system name and version
• default language

This is how websites can collect certain general information about their surfers' systems. For example, they can detect if the surfer is using a cellphone browser and redirect them to a mobile version of their website which works better on smaller screens.

In PHP, it can be found with: $_SERVER['HTTP_USER_AGENT'].  1 if ( strstr($_SERVER['HTTP_USER_AGENT'],'MSIE 6') ) {  2  echo "Please stop using IE6!";  3 } 

#### Accept-Language

 1 Accept-Language: en-us,en;q=0.5 

This header displays the default language setting of the user. If a website has different language versions, it can redirect a new surfer based on this data.

It can carry multiple languages, separated by commas. The first one is the preferred language, and each other listed language can carry a "q" value, which is an estimate of the user's preference for the language (min. 0 max. 1).

In PHP, it can be found as: $_SERVER["HTTP_ACCEPT_LANGUAGE"].  1 if (substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2) == 'fr') {  2  header('Location: http://french.mydomain.com');  3 } 

#### Accept-Encoding

 1 Accept-Encoding: gzip,deflate 

Most modern browsers support gzip and will send this in the header. The web server then can send the HTML output in a compressed format. This can reduce the size by up to 80% to save bandwidth and time.

In PHP, it can be found as: $_SERVER["HTTP_ACCEPT_ENCODING"]. However, when you use the ob_gzhandler() callback function, it will check this value automatically, so you don't need to.  1 // enables output buffering  2 // and all output is compressed if the browser supports it  3 ob_start('ob_gzhandler');  #### If-Modified-Since If a web document is already cached in your browser, and you visit it again, your browser can check if the document has been updated by sending this:  1 If-Modified-Since: Sat, 28 Nov 2009 06:38:19 GMT  If it was not modified since that date, the server will send a "304 Not Modified" response code, and no content—and the browser will load the content from the cache. In PHP, it can be found as: $_SERVER['HTTP_IF_MODIFIED_SINCE'].

 1 // assume $last_modify_time was the last the output was updated  2 3 // did the browser send If-Modified-Since header?  4 if(isset($_SERVER['HTTP_IF_MODIFIED_SINCE'])) {  5 6  // if the browser cache matches the modify time  7  if ($last_modify_time == strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE'])) {  8 9  // send a 304 header, and no content  10  header("HTTP/1.1 304 Not Modified");  11  exit;  12  }  13 14 } 

There is also an HTTP header named Etag, which can be used to make sure the cache is current. We'll talk about this shortly.

#### Cookie

As the name suggests, this sends the cookies stored in your browser for that domain.

 1 Cookie: PHPSESSID=r2t5uvjq435r4q7ib3vtdjq120; foo=bar 

These are name=value pairs separated by semicolons. Cookies can also contain the session id.

In PHP, individual cookies can be accessed with the $_COOKIE array. You can directly access the session variables using the $_SESSION array, and if you need the session id, you can use the session_id() function instead of the cookie.

 1 echo $_COOKIE['foo'];  2 // output: bar  3 echo$_COOKIE['PHPSESSID'];  4 // output: r2t5uvjq435r4q7ib3vtdjq120  5 session_start();  6 echo session_id();  7 // output: r2t5uvjq435r4q7ib3vtdjq120 

#### Referer

As the name suggests, this HTTP header contains the referring URL.

For example, if I visit the Envato Tuts+ Code homepage and click on an article link, this header is sent to my browser:

 1 Referer: https://code.tutsplus.com/ 

In PHP, it can be found as $_SERVER['HTTP_REFERER'].  1 if (isset($_SERVER['HTTP_REFERER'])) {  2 3  $url_info = parse_url($_SERVER['HTTP_REFERER']);  4 5  // is the surfer coming from Google?  6  if ($url_info['host'] == 'www.google.com') {  7 8  parse_str($url_info['query'], $vars);  9 10  echo "You searched on Google for this keyword: ".$vars['q'];  11 12  }  13 14 }  15 // if the referring URL was:  16 // http://www.google.com/search?source=ig&hl=en&rlz=&=&q=http+headers&aq=f&oq=&aqi=g-p1g9  17 // the output will be:  18 // You searched on Google for this keyword: http headers 

You may have noticed the word "referrer" is misspelled as "referer". Unfortunately it made into the official HTTP specifications like that and got stuck.

#### Authorization

When a web page asks for authorization, the browser opens a login window. When you enter a username and password in this window, the browser sends another HTTP request, but this time it contains this header.

 1 Authorization: Basic bXl1c2VyOm15cGFzcw== 

The data inside the header is base64 encoded. For example, base64_decode('bXl1c2VyOm15cGFzcw==') would return 'myuser:mypass'.

In PHP, these values can be found as $_SERVER['PHP_AUTH_USER'] and $_SERVER['PHP_AUTH_PW'].

### HTTP Headers in HTTP Responses

Now we are going to look at some of the most common HTTP headers found in HTTP responses.

In PHP, you can set response headers using the header() function. PHP already sends certain headers automatically, for loading the content, setting cookies, etc. You can see the headers that are sent, or will be sent, with the headers_list() function. You can check if the headers have been sent already with the headers_sent() function.

#### Cache-Control

Here's the definition from w3.org:

The Cache-Control general-header field is used to specify directives which MUST be obeyed by all caching mechanisms along the request/response chain.

These "caching mechanisms" include gateways and proxies that your ISP may be using.

For example:

 1 Cache-Control: max-age=3600, public 

public means that the response may be cached by anyone. max-age indicates how many seconds the cache is valid for. Allowing your website to be cached can reduce server load and bandwidth, as well as improving load times in the browser.

Caching can also be prevented by using the no-cache directive.

 1 Cache-Control: no-cache 

For more detailed info, see w3.org.

#### Content-Type

This header indicates the "MIME type" of the document. The browser then decides how to interpret the contents based on this. For example, an HTML page (or a PHP script with HTML output) may return this:

 1 Content-Type: text/html; charset=UTF-8 

text is the type, and html is the subtype of the document. The header can also contain more information, such as charset.

For a GIF image, this may be sent:

 1 Content-Type: image/gif 

The browser can decide to use an external application or browser extension based on the MIME type. For example, this will cause Adobe Reader or the browser's built-in PDF reader to be loaded:

 1 Content-Type: application/pdf 

When loading directly, Apache can usually detect the MIME type of a document and send the appropriate header. Also, most browsers have some amount of fault tolerance and auto-detection of the MIME types, in case the headers are wrong or not present.

You can find a list of common MIME types in the MDN Web Docs.

In PHP, you can use the finfo_file() function to detect the MIME type of a file.

#### Content-Disposition

 1 Content-Disposition: attachment; filename="download.zip" 

That will cause the browser to do this:

Note that the appropriate Content-Type header should also be sent along with this:

 1 Content-Type: application/zip  2 Content-Disposition: attachment; filename="download.zip" 

#### Content-Length

When content is going to be transmitted to the browser, the server can indicate its size (in bytes) using this header.

 1 Content-Length: 89123 

For example, here is a dummy script I wrote, which simulates a large download.

 1 // it's a zip file  2 header('Content-Type: application/zip');  3 // 1 million bytes (about 1megabyte)  4 header('Content-Length: 1000000');  5 // load a download dialogue, and save it as download.zip  6 header('Content-Disposition: attachment; filename="download.zip"');  7 8 // 1000 times 1000 bytes of data  9 for ($i = 0;$i < 1000; $i++) {  10  echo str_repeat(".",1000);  11 12  // sleep to slow down the download  13  usleep(50000);  14 }  The result is: Now I am going to comment out the Content-Length header:  1 // it's a zip file  2 header('Content-Type: application/zip');  3 // the browser won't know the size  4 // header('Content-Length: 1000000');  5 // load a download dialogue, and save it as download.zip  6 header('Content-Disposition: attachment; filename="download.zip"');  7 8 // 1000 times 1000 bytes of data  9 for ($i = 0; $i < 1000;$i++) {  10  echo str_repeat(".",1000);  11 12  // sleep to slow down the download  13  usleep(50000);  14 } 

Now the result is:

The browser can only tell you how many bytes have been downloaded, but it does not know the total amount. And the progress bar is not showing the progress.

#### Etag

This is another header that is used for caching purposes. It looks like this:

 1 Etag: "pub1259380237;gz" 

The web server may send this header with every document it serves. The value can be based on the last modify date, the file size, or even the checksum value of a file. The browser then saves this value as it caches the document. The next time the browser requests the same file, it sends this in the HTTP request:

 1 If-None-Match: "pub1259380237;gz" 

If the Etag value of the document matches that, the server will send a 304 code instead of 200, and no content. The browser will load the contents from its cache.

#### Last-Modified

As the name suggests, this header indicates the last modify date of the document, in GMT format:

 1 Last-Modified: Sat, 28 Nov 2009 03:50:37 GMT 
 1 $modify_time = filemtime($file);  2 3 header("Last-Modified: " . gmdate("D, d M Y H:i:s", $modify_time) . " GMT");  It offers another way for the browser to cache a document. The browser may send this in the HTTP request:  1 If-Modified-Since: Sat, 28 Nov 2009 06:38:19 GMT  We already talked about this earlier, in the If-Modified-Since section. #### Location This header is used for redirections. If the response code is 301 or 302, the server must also send this header. For example, when you go to https://code.tutsplus.com, your browser will receive this:  1 HTTP/1.x 301 Moved Permanently  2 ...  3 Location: https://code.tutsplus.com/  4 ...  In PHP, you can redirect a surfer like so:  1 header('Location: https://code.tutsplus.com/');  By default, that will send a 302 response code. If you want to send a 301 instead:  1 header('Location: https://code.tutsplus.com/', true, 301);  #### Set-Cookie When a website wants to set or update a cookie in your browser, it will use this header.  1 Set-Cookie: skin=noskin; path=/; domain=.amazon.com; expires=Sun, 29-Nov-2009 21:42:28 GMT  2 Set-Cookie: session-id=120-7333518-8165026; path=/; domain=.amazon.com; expires=Sat Feb 27 08:00:00 2010 GMT  Each cookie is sent as a separate header. Note that cookies set via JavaScript do not go through HTTP headers. In PHP, you can set cookies using the setcookie() function, and PHP sends the appropriate HTTP headers.  1 setcookie("TestCookie", "foobar");  Which causes this header to be sent:  1 Set-Cookie: TestCookie=foobar  If the expiration date is not specified, the cookie is deleted when the browser window is closed. #### WWW-Authenticate A website may send this header to authenticate a user through HTTP. When the browser sees this header, it will open up a login dialogue window.  1 WWW-Authenticate: Basic realm="Restricted Area"  Which looks like this: There is a section in the PHP manual that has code samples on how to do this in PHP.  1 if (!isset($_SERVER['PHP_AUTH_USER'])) {  2  header('WWW-Authenticate: Basic realm="My Realm"');  3  header('HTTP/1.0 401 Unauthorized');  4  echo 'Text to send if user hits Cancel button';  5  exit;  6 } else {  7  echo "

Hello {$_SERVER['PHP_AUTH_USER']}. ";  8  echo " You entered {$_SERVER['PHP_AUTH_PW']} as your password.

";  9 } 

#### Content-Encoding

This header is usually set when the returned content is compressed.

 1 Content-Encoding: gzip 

In PHP, if you use the ob_gzhandler() callback function, it will be set automatically for you.

## How to Send HTTP Headers

After reading the tutorial up to this point, you should have a good idea of what HTTP headers are and what their different values mean. Some headers are sent and received automatically when you make a request to a server and get a response back.

However, there will be situations where you want to send your own custom headers besides the ones sent by the client or server.

One of the most common ways of sending your own headers in a request is by using the cURL library in PHP. The library comes with a bunch of functions to handle all your needs. There are four basic steps involved:

1. You use curl_init() to start your cURL session. You can pass it the URL you want to request.
2. The curl_setopt() function is used to configure the request according to your needs. This is where you can set your own headers by using the CURLOPT_HTTPHEADER option.
3. After you have set all the options, you can execute the request by calling curl_exec().
4. Finally, you can close the session by calling the curl_close() function.

Here is a basic example that sends a request to https://code.tutsplus.com/tutorials.

 1  

If you want to send response headers in PHP, then you should use the header() function. Among other things, one common use is redirecting visitors to other pages. This can be done by using the Location header. Here is an example:

 1  

You have to remember to call the header() function before any kind of output either in HTML or in PHP. Even blank output is not permitted. Otherwise, you will get the Headers already sent error.

## Conclusion

Thanks for reading. I hope this article was a good starting point for learning about HTTP headers. If you want to take your web development further, check out some of the popular files on CodeCanyon. These scripts, apps, templates, and plugins can save you precious development time and help you add new features quickly and easily.

### The Best PHP Scripts on CodeCanyon

Explore thousands of the best and most useful PHP scripts ever created on CodeCanyon.

Here are a few of the best-selling and up-and-coming PHP scripts available on CodeCanyon for 2021.

This post has been updated with contributions from Monty Shokeen. Monty is a full-stack developer who also loves to write tutorials, and to learn about new JavaScript libraries.