O'Reilly logo

PHP in a Nutshell by Paul Hudson

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

HTTP

Hypertext Transport Protocol is a primarily a basic protocol to handle data transmission, but it is also capable of authentication and more. PHP gives you all the tools you need to manipulate HTTP for your own needs.

Sending Custom Headers

There are several special HTTP headers you can send to instruct the remote client. For example, the "Location" header instructs browsers to request a different URL, the "Content-Type" header tells browsers what kind of content they are about to receive, and the "WWW-Authenticate" header tells browsers that they need to send some authentication information to proceed.

Sending custom headers in PHP is done using the header() function, which takes the header to send as its parameter. So, to make a browser go to www.example.com when it visits a certain script, this would be used:

    header("Location: http://www.example.com");

Special attention should be paid when using the Location header, however, as it is used to redirect clients from one page to another. When you send a Location header, the rest of your script will still be executed, potentially allowing people to see pages they would otherwise not be able to see. As a result, it's best to call exit immediately after header("Location: ...") to ensure that nothing happens after the redirect notice has been sent.

The headers_sent() function, when called with no parameters, returns true if your HTTP headers have been sent or false otherwise. That isn't "whether some headers have been sent" but "whether ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required