Skip to Content
PHP Cookbook
book

PHP Cookbook

by David Sklar, Adam Trachtenberg
November 2002
Intermediate to advanced
640 pages
16h 33m
English
O'Reilly Media, Inc.
Content preview from PHP Cookbook

8.4. 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 the data.

Solution

Before any output is printed, use header( ) to send a Location header with the new URL:

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

Discussion

If you want to pass variables to the new page, you can include them in the query string of the URL:

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

The URL that you are redirecting a user to is retrieved with GET. You can’t redirect someone to retrieve a URL via POST. You can, however, send other headers along with the Location header. This is especially useful with the Window-target header, which indicates a particular named frame or window in which to load the new URL:

header('Window-target: main');
header('Location: http://www.example.com/');

The redirect URL must include the protocol and hostname; it can’t just be a pathname:

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

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

See Also

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

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

PHP Cookbook

PHP Cookbook

Eric A. Mann
PHP Cookbook, 2nd Edition

PHP Cookbook, 2nd Edition

Adam Trachtenberg, David Sklar
PHP Cookbook, 3rd Edition

PHP Cookbook, 3rd Edition

David Sklar, Adam Trachtenberg
Programming PHP

Programming PHP

Rasmus Lerdorf, Kevin Tatroe

Publisher Resources

ISBN: 1565926811Supplemental ContentCatalog PageErrata