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 ...

Get PHP in a Nutshell now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.