Respond and redirect with PHP

An excerpt from the third edition of PHP Cookbook

Editor’s Note: The following excerpt is from the third edition of PHP Cookbook by David Sklar and Adam Trachtenberg. For those already familiar with PHP, PHP Cookbook shows you how to overcome specific problems in your everyday work. Programmers coming from other languages will also find recipes helpful which demonstrate how to accomplish a particular task in PHP, such as sending email or parsing JSON, that you may already know how to do in another language. The recipes are self-contained in a simple problem-solution-discussion format with explanations of how and why the code works the way it does.

This cookbook arms PHP developers with important information for key PHP updates, particularly data manipulation, web services, internationalization, database access, security, and testing. This excerpt, from the chapter focused on Web Fundamentals, demonstrates how to set the HTTP Status Code and how to redirect a user to a different web page than the one they requested. Portions of this chapter have been edited and condensed for the purposes of this excerpt.


Sending a specific HTTP Status Code

Problem

You want to explicitly set the HTTP Status Code. For example, you want to indicate that the user is unauthorized to view the page or the page is not found.

Solution

Use http_response_code(  ) to set the response:

<?php
http_response_code(401);

Discussion

Your Web server returns HTTP Status Code 200 (OK) for most pages processed by PHP. But there are a wide range of Status Codes, or response codes, that you may need to use.

A few popular codes get Recipes of their own. When you’re redirecting to a different page, you need to send a 302 (Found) Status Code. This is covered in “Redirecting to a Different Location.” When a person is not allowed to view a page, you send a 401 (Unauthorized).

But there’s always 304 (Not Modified) for conditional GETs. This can be used when someone is polling your site and you want to tell them there’s nothing new to retrieve.

Or, the infamous 404 (Not Found), when a page isn’t there. Normally, this is handled by your Web server. But if you want to support dynamic URLs, where there aren’t physical files stored on a disk, but you process the URL and respond to it based on information in a database, then you need to handle this yourself when someone tries to fetch an invalid URL.

One great example is WordPress, which responds to URLs based on categories or dates (e.g /category/php/ or /2014/11/03/). In these cases, whenever someone adds a category or a post on a new data, WordPress can be configured to automatically respond to requests at URLs that match that pattern, even though there aren’t actually files at that location.

With http_response_code(  ), you provide the Status Code number and PHP takes care of setting the proper Status Line. For some Status Codes, including 204 (No Content), the HTTP specification states you must not provide a message body. In these cases, it’s best to send exit( ) to immediately end the script. This prevents content from being accidentally added later on.

<?php
http_response_code(401);
exit();

If you’re stuck on PHP 5.3, use header( ), and pass in the Status Code as the 3rd parameter:

<?php
header('HTTP/1.0 401 Unauthorized');

See Also

The HTTP 1.1 Specification’s description of Status Codes at http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html.

Redirecting to a Different Location

Problem

You want to automatically send a user to a new URL. For example, after successfully saving form data, you want to redirect a user to a page that confirms that the data has been saved.

Solution

Before any output is printed, use header(  ) to send a Location header with the new URL, and then call exit(  ) so that nothing else is printed:

<?php
header('Location: http://www.example.com/confirm.html');
exit();

Discussion

To pass variables to the new page, include them in the query string of the URL, as in Example 1-1.

Example 1-1. Redirecting with query string variables

<?php
header('Location: http://www.example.com/?monkey=turtle');
exit();

Redirect URLs must include the protocol and hostname. They cannot be just a pathname. Example 1-2 shows a good Location header and a bad one.

Example 1-2.Good and bad location headers

<?php
// Good Redirect
header('Location: http://www.example.com/catalog/food/pemmican.php');

// Bad Redirect
header('Location: /catalog/food/pemmican.php');

The URL that you are redirecting a user to is retrieved with GET. You can’t redirect someone to retrieve a URL via POST. With JavaScript, however, you can simulate a redirect via POST by generating a form that gets submitted (via POST) automatically. When a (JavaScript-enabled) browser receives the page in Example 1-3, it will immediately POST the form that is included.

Example 1-3.Redirecting via a posted form

html
<body onload="document.getElementById('redirectForm').submit()">
<form id='redirectForm' method='POST' action='/done.html'>
<input type='hidden' name='status' value='complete'/>
<input type='hidden' name='id' value='0u812'/>
<input type='submit' value='Please Click Here To Continue'/>
</form>
</body>
</html>

The form in Example 1-3 has an id of redirectForm, so the code in the <body/> element’s onload attribute submits the form. The onload action does not execute if the browser has JavaScript disabled. In that situation, the user sees a Please Click Here To Continue button.

See Also

Documentation on header(  ) at http://www.php.net/header.

tags: ,