To perform a redirect in PHP, use the header()
function with the Location
header. Here’s how to do it correctly, along with best practices and common scenarios:
Basic Redirect
<?php
// Redirect to another page
header("Location: https://example.com/new-page.php");
exit(); // Always exit/die after redirect to halt script execution
?>
Key Considerations
- No Output Before Redirect:
Ensure no content (HTML,echo
, whitespace, etc.) is sent to the browser before callingheader()
.
- Common Error:
Cannot modify header information – headers already sent
. - Fix: Use output buffering (
ob_start()
) or structure code to avoid early output.
- Absolute vs. Relative URLs:
Use absolute URLs for reliability:
header("Location: http://www.yoursite.com/new-page.php"); // Recommended
// header("Location: /new-page.php"); // Relative (works but not always reliable)
- HTTP Status Codes:
Specify a status code for permanent (301) or temporary (302) redirects:
header("HTTP/1.1 301 Moved Permanently"); // Permanent redirect
header("Location: https://example.com/new-url.php");
exit();
Advanced Scenarios
Redirect After a Delay (Meta Refresh)
Use if headers are already sent (not recommended for critical redirects):
<?php
echo '<meta http-equiv="refresh" content="5; url=https://example.com/new-page.php">';
echo "You will be redirected in 5 seconds...";
// Use this only as a fallback
?>
Conditional Redirect
<?php
if ($user_not_logged_in) {
header("Location: login.php");
exit();
}
?>
Redirect to Dynamic URL
<?php
$id = 123;
header("Location: profile.php?id=$id");
exit();
?>
Security Tips
- Validate Redirects: Avoid open redirects (e.g.,
header("Location: " . $_GET['url']);
) to prevent phishing risks. - Sanitize Input: If using dynamic URLs, sanitize parameters:
$safe_url = filter_var($_GET['url'], FILTER_SANITIZE_URL);
header("Location: $safe_url");
Troubleshooting
- Check Headers: Use
headers_sent()
to debug:
if (!headers_sent()) {
header("Location: https://example.com");
exit();
} else {
echo "Headers already sent – redirect failed!";
}
- Test with cURL:
Runcurl -I http://yoursite.com
to inspect response headers.
Summary
- Use
header("Location: url");
for immediate redirects. - Always follow with
exit()
ordie()
. - Avoid output before headers and validate URLs for security.