user7749092
user7749092

Reputation:

why does 'location' header field redirects immediately and other header fields don't when used with header() function in php

According to the PHP Manual

header() — Send a raw HTTP header

Now,

when I use following code :

header('location:form.html');

then, the header function immediately redirects the browser to form.html OR simply an HTTP response header is sent immediately after the execution of above line.

but when I use same header function to add some other header fields to the response header, for example:

header("X-Sample-Test: foo");
header('Content-type: text/plain');

then why doesn't it send an HTTP response header immediately?

First of all, correct me if I am wrong and secondly please do share more information on HTTP headers.

Upvotes: 0

Views: 584

Answers (1)

Sᴀᴍ Onᴇᴌᴀ
Sᴀᴍ Onᴇᴌᴀ

Reputation: 8297

As was alluded to in a comment, the PHP.net documentation states that:

The second special case is the "Location:" header. Not only does it send this header back to the browser, but it also returns a REDIRECT (302) status code to the browser unless the 201 or a 3xx status code has already been set.1.

Thus that header is a special case.

but when I use same header function to add some other header fields to the response header

header("X-Sample-Test: foo");
header('Content-type: text/plain');

then why don't it sends a HTTP response header immediately.

It still sends those headers (you should be able to see them in a browser console - e.g. In a networking tab) but the browser doesn't send the user to a different URL like it does for a redirect header.

Take a look at the image below, where I inspected the response headers in the network tab after loading a PHP page with those headers. I highlighted those headers coming through. For more information about viewing headers see these answers for Google Chrome or Mozilla Firefox.

inspecting headers

You may find it interesting to read some of the (positive-voted) user contributed notes on that documentation page.


1http://php.net/manual/en/function.header.php

Upvotes: 1

Related Questions