How to Redirect Page in PHP: Simple Guide with Examples
To redirect a page in PHP, use the
header('Location: URL') function before any output is sent to the browser. This sends an HTTP redirect response telling the browser to load the new URL.Syntax
The basic syntax to redirect in PHP is using the header function with the Location header. It looks like this:
header('Location: URL');- tells the browser to go to the specified URL.- Make sure to call
exit();right after to stop the script. - Do this before any HTML or output is sent, or it will cause an error.
php
<?php
header('Location: https://example.com');
exit();
?>Example
This example shows how to redirect a user to "https://example.com" when they visit the PHP page. It stops the script after redirecting to avoid running any more code.
php
<?php // Redirect to example.com header('Location: https://example.com'); exit(); ?>
Output
The browser immediately loads https://example.com instead of showing this page.
Common Pitfalls
Common mistakes when redirecting in PHP include:
- Sending output (like HTML or echo) before
header()causes an error because headers must be sent first. - Not calling
exit()afterheader()can let the script continue running, which may cause unexpected behavior. - Using relative URLs without a proper base can cause wrong redirects.
php
<?php // Wrong way - output sent before header // echo 'Hello'; // header('Location: https://example.com'); // This causes error // Right way header('Location: https://example.com'); exit();
Quick Reference
Remember these quick tips for PHP redirects:
- Use
header('Location: URL');to redirect. - Call
exit();immediately after. - Do not send any output before
header(). - Use full URLs for clarity.
Key Takeaways
Always use
header('Location: URL'); before any output to redirect in PHP.Call
exit(); right after header() to stop script execution.Never send HTML or echo before calling
header() to avoid errors.Use full URLs in the Location header for reliable redirects.