How to Redirect URL in PHP Using header()
Redirecting a user to a different web page is a fundamental task in
web development. This article provides a quick and straightforward guide
on how to perform a URL redirect in PHP using the native
header() function. You will learn the correct syntax, the
essential best practices to prevent security vulnerabilities, and how to
send the correct HTTP status codes for temporary or permanent
redirects.
The Basic Redirect Syntax
To redirect a user to another page, you pass the
Location header followed by the target URL to the PHP
header() function.
Here is the standard implementation:
<?php
header("Location: https://www.example.com/target-page.php");
exit;
?>Why You Must Use exit
or die()
Immediately after calling the header() function, you
must call exit; or die();.
The header() function instructs the user’s browser to
redirect, but it does not stop the PHP engine from executing the rest of
the script. If you omit exit, the server will continue to
execute any code below the redirect, which can consume server resources
or lead to security vulnerabilities where unauthorized users see content
they shouldn’t.
The “Headers Already Sent” Error
The header() function must be called
before any actual output is sent to the browser. This
includes: * HTML tags (e.g., <html>,
<body>) * Empty lines, spaces, or line breaks before
the opening <?php tag * PHP echo or
print statements
If any output is sent before the header() function is
executed, PHP will trigger a “headers already sent” warning, and the
redirect will fail.
Handling HTTP Status Codes (301 vs. 302)
By default, PHP sends a 302 Found status code, which indicates a temporary redirect. If you want to perform a permanent redirect (for SEO purposes when a page has moved permanently), you should explicitly send a 301 Moved Permanently status code.
302 Temporary Redirect (Default)
<?php
header("Location: https://www.example.com/temporary-page.php", true, 302);
exit;
?>301 Permanent Redirect
<?php
header("Location: https://www.example.com/new-permanent-page.php", true, 301);
exit;
?>The second parameter (true) defines whether the header
should replace a previous similar header, and the third parameter
specifies the HTTP response code.
Relative vs. Absolute URLs
While modern web browsers can resolve relative URLs (e.g.,
header("Location: /login.php")), the HTTP/1.1 specification
technically requires an absolute URI containing the protocol and domain
name (e.g.,
header("Location: https://www.example.com/login.php")).
Using absolute URLs is recommended to ensure compatibility across all
user clients and search engine crawlers.