How to make a PHP redirect
A PHP redirect is a server-side method that uses the PHP header() function to send a user’s browser to a different URL.
Its main purpose is to manage flow control, improve user experience by guiding users to the right content, and support search engine optimization (SEO) by informing search engines of page updates.
To implement a redirect in PHP, you use the header() function to send an HTTP Location header to the browser.
This command must be executed before any HTML or text is sent, and it’s best practice to include an exit; command immediately after to stop the script from running.
How to redirect using PHP’s header() function
To redirect a user to another page in PHP, you use the header() function to specify the new location.
The basic syntax looks like this:
<?php
// Redirect to a new page
header("Location: newpage.php");
exit; // This stops the script from executing after the redirect
?>
The most important rule for the header() function is that it must be called before any output is sent to the browser. This includes any HTML, whitespace, or even an echo statement.
Basic PHP redirect examples
Here’s a basic PHP redirect example of redirecting to another page within your same website (a relative URL):
<?php
// Redirects to contact-us.php in the same directory
header("Location: contact-us.php");
exit;
?>
The example below shows how to redirect to a completely different website (an absolute URL):
<?php
// Redirects to Google
header("Location: https://www.google.com");
exit;
?>
Important! Always include exit; or die(); right after the header() function. This prevents the rest of the script from running, which is a crucial security and flow control measure.
PHP redirect with status codes (301 or 302)
To perform a redirect in PHP with specific HTTP status codes like 301 or 302, you add the status code as an optional parameter to the header() function.
By default, header(‘Location: …’) sends a 302 temporary redirect. To add a specific code, you use the function’s optional parameters: header(“Location: URL”, true, 301).
The true parameter forces the function to replace any existing header, and 301 is the HTTP code you’re sending.
Use 301 Permanent Redirect when a page’s URL has changed permanently. This has significant SEO value as it tells search engines to update their index and passes ranking signals to the new one.
Choose 302 Temporary Redirect if you’re redirecting temporarily (like for maintenance) and plan to use the old URL again. This tells search engines not to update their index, as the original page will return.
<?php
// Temporary redirect
header("Location: https://www.domain.tld/maintenance.php", true, 302);
exit;
?>
If you encounter the “headers already sent” error, it might be due to whitespace or other settings in your php.ini file. Learn more about the PHP configuration file to help you troubleshoot the issue.
What are conditional redirects in PHP?
Conditional redirects in PHP involve using if statements or other logical expressions to determine whether a redirect should occur.
This lets you create dynamic and smarter navigation flows for your users, sending them to the right page based on specific criteria.
For example, you can check if a user is logged in before displaying a members-only page, or send users to a mobile-optimized version of your site if they are accessing it from a phone.
PHP redirect after login or based on the session
Redirecting a user after login or based on a session in PHP involves checking a $_SESSION variable to see if they are authenticated.
To do so, start the session at the top of your script with session_start();.
The following script checks if a user_id is set in the session. If not, it redirects the user to the login page.
<?php
session_start();
// Check if the user is logged in
if (!isset($_SESSION['user_id'])) {
// User is not logged in, redirect to login page
header("Location: login.php");
exit;
}
// If we get here, the user is logged in
// Continue loading the protected page content...
echo "Welcome to the members-only area!";
?>
Conversely, on your login processing page, you would redirect them to the dashboard after you successfully verify their credentials and set the session:
<?php
// (After verifying username and password...)
// Set session variable
$_SESSION['user_id'] = $user_id_from_db;
// Redirect to the user dashboard
header("Location: dashboard.php");
exit;
?>
PHP redirect based on user device
Redirecting users in PHP based on their device involves checking the HTTP_USER_AGENT string. This string, available in the $_SERVER superglobal, contains information about the user’s browser and operating system.
While user agent sniffing can be unreliable, a simple check for common mobile keywords can work for basic redirects.
<?php
// Get the user agent string
$user_agent = $_SERVER['HTTP_USER_AGENT'];
// Array of mobile keywords
$mobile_keywords = ['Mobile', 'Android', 'iPhone', 'iPad', 'Windows Phone'];
$is_mobile = false;
// Check if any mobile keyword is present in the user agent
foreach ($mobile_keywords as $keyword) {
if (strpos($user_agent, $keyword) !== false) {
$is_mobile = true;
break; // Found a mobile keyword, no need to check further
}
}
// If it's a mobile device, redirect to the mobile site
if ($is_mobile) {
header("Location: https://m.domain.tld");
exit;
}
// Otherwise, load the desktop site
// ...
?>
Important! This method isn’t foolproof. A more robust solution is to use responsive design, which adapts your site’s layout to the screen size without needing any redirects.
What are the alternatives for redirecting in PHP?
While header(‘Location: …’) is the standard and most robust method for server-side redirects in PHP, alternatives exist, primarily for client-side redirection or as fallbacks.
These are useful if you’ve already sent output and can no longer use the header() function.
- JavaScript redirect. This happens entirely in the user’s browser. It’s less ideal for SEO, as it doesn’t signal a 301/302 status, may be missed by crawlers, and fails if JavaScript is disabled. However, it works as a fallback after the page has started loading.
<script>
window.location.replace("https://www.domain.tld/new-page.html");
</script>
- HTML meta refresh. This is an old HTML tag that tells the browser to refresh or redirect to a new URL after a specified amount of time. A delay of 0 seconds makes it an instant redirect.
<meta http-equiv="refresh" content="0;url=https://www.domain.tld/new-page.html">
- Framework helpers. Modern frameworks often provide built-in functions that are easier to manage than raw headers. For instance, use the CodeIgniter redirect helper or Laravel’s redirect() helper (which you can manage after installing Composer).
The header() function should always be your first choice. Use client-side alternatives only when a server-side redirect is technically impossible (like when headers are already sent).
Never use client-side redirects for sensitive operations like authentication or access control, as they can be easily bypassed.
For accessibility, some screen readers handle meta refreshes better than JavaScript redirects, but both are less secure than header().
If you want to explore more robust options for building your application beyond standard PHP scripts, check out our guide to the best PHP frameworks.
Next steps: How to handle PHP errors
Redirect failures primarily stem from misconfiguration and output issues because no output can be sent to the browser before the header() function is called.
The single most common error you will encounter is:
Warning: Cannot modify header information - headers already sent
This error means something was sent to the browser before your header() function was called. This can be:
- HTML. Any HTML tags, even a <!DOCTYPE> declaration.
- Whitespace. A space or new line before your opening <?php tag in any file.
- PHP output. Any echo or print statement.
- Error messages. A PHP notice or warning is being displayed.
- BOM (byte-order mark). Invisible characters added if a file is saved with UTF-8 BOM encoding, which can happen in some legacy text editors.
To fix this, trace your code’s execution and find where the first output is being sent. Check for any echo or print statements, HTML outside of <?php … ?> tags, or even whitespace before your opening <?php tag.
If the error persists, check any files that are included or required before the redirect logic is executed.
All of the tutorial content on this website is subject to Hostinger's rigorous editorial standards and values.