Redirect to another page in PHP

Redirect to another page in PHP

Modified
Sep 19, 2023
Written by
Benjamin Crozat
0
comments
3 minutes
read

How to perform a redirection

To redirect to another page using PHP, run the following code:

// Ensure nothing is echoed before setting the header.
header('Location: http://example.com');

exit;

Understanding the code

  1. First, ensure no output has been sent before setting headers. Even a simple space or an unintended echo can break your redirection.
  2. Then, use the header() function to instruct the visitor’s browser to redirect to the specified URL.
  3. Finally, use exit to terminate execution immediately. Technically optional, but practically mandatory to prevent unintended code execution afterward.

Essentially, PHP sends an HTTP response that tells your visitor’s browser to redirect to the provided URL.

Anatomy of an HTTP response

Here’s a basic HTTP response example:

HTTP/1.1 302 Found
Content-Type: text/html
Location: http://example.com

<html>
    <p>This is a redirection.</p>
</html>

Let’s break it down:

  1. The status line containing:
    • HTTP version used.
    • Status code (302 here).
    • A reason phrase (“Found”).
  2. Headers, including Location, which points the browser where to redirect.
  3. Optional body, often omitted for redirects.

Remember, echoing or outputting any text before headers causes the infamous PHP error: "headers already sent". This happens because PHP must send headers before any other content. Always double-check for unintended outputs.

Which URL format to use?

Always prefer absolute URLs (e.g., http://example.com). Relative URLs (/path) usually work but might fail with some clients or proxies, causing unexpected behavior.

Choosing the correct HTTP status code

By default, PHP uses 302 Found:

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

To set a permanent redirect (301 Moved Permanently), specify it explicitly:

header('Location: http://example.com', response_code: 301);

Status codes quick reference:

Code When to Use Behavior
301 Permanent move (SEO friendly) Aggressively cached; method changes to GET
302 Temporary redirect (default) Rarely cached; method changes to GET
303 After form submission (PRG pattern) Method explicitly changes to GET
307 Temporary redirect, method preserved Rarely cached; method retained
308 Permanent redirect, method preserved Aggressively cached; method retained

SEO and caching warnings

Be cautious: 301 and 308 redirects are cached by browsers and CDNs. Reverting these redirects later can be tricky. For temporary changes or A/B tests, prefer 302, 303, or 307 to avoid caching headaches.

Security tip: Avoid open redirects

Never redirect to URLs directly from user input without validation. You might inadvertently enable phishing. Here’s a safe way:

$next = $_GET['next'] ?? '/';

if (!preg_match('#^/[\w/-]*$#', $next)) {
    $next = '/';
}

header("Location: $next", true, 303);

exit;

Clearer redirection code (optional)

PHP also offers a clearer, more readable way to set headers and HTTP codes:

http_response_code(301);

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

exit;

Verifying your redirects

You can test your redirection easily with the command line using curl:

curl -I http://your-site.com/old-page

You’ll see something like:

HTTP/1.1 301 Moved Permanently
Location: http://your-site.com/new-page

Alternatively, use your browser’s developer tools network tab to see redirection details clearly.

With these tips, your PHP redirects are now robust, secure, and reliable.


Did you like this article? Then, keep learning:

0 comments