
Redirect to another page in PHP
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
- First, ensure no output has been sent before setting headers. Even a simple space or an unintended echo can break your redirection.
- Then, use the
header()
function to instruct the visitor’s browser to redirect to the specified URL. - 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:
- The status line containing:
- HTTP version used.
- Status code (302 here).
- A reason phrase (“Found”).
- Headers, including
Location
, which points the browser where to redirect. - 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:
- Explore PHP 8.4's new features for up-to-date coding practices
- Know how to find out your PHP version quickly and easily
- Learn how to convert PHP arrays to JSON for APIs and data exchange
- Master handling PHP exceptions using try and catch blocks
- Master printing arrays in PHP for better debugging experiences
- Improve your code with PHP's null coalescing operator explained
- Learn different types of PHP redirections beyond basics
- Debug PHP code effectively by showing all errors plainly
- Understand and solve common PHP errors like $this in non-object context
0 comments