How to Use Header for Redirect in PHP: Simple Guide
In PHP, you can redirect users to another page by using the
header function with the Location header, like header('Location: target.php');. Make sure to call exit() right after to stop the script and avoid sending extra output.Syntax
The header function sends a raw HTTP header to the browser. To redirect, use the Location header with the target URL.
- header('Location: URL'): Tells the browser to go to the URL.
- exit(): Stops the script to prevent further output.
php
header('Location: https://example.com');
exit();Example
This example redirects the user to https://example.com immediately when the script runs.
php
<?php // Redirect to example.com header('Location: https://example.com'); exit(); ?>
Output
The browser redirects to https://example.com immediately.
Common Pitfalls
Common mistakes when using header for redirect include:
- Sending any output (like HTML or echo) before calling
header. This causes an error because headers must be sent first. - Not calling
exit()afterheader, which can lead to unwanted code running. - Using relative URLs incorrectly or forgetting the full path.
php
<?php // Wrong way: output before header // echo 'Redirecting...'; // header('Location: https://example.com'); // exit(); // Right way: header('Location: https://example.com'); exit();
Quick Reference
| Action | Code Example | Notes |
|---|---|---|
| Redirect to URL | header('Location: https://example.com'); | Must be called before any output |
| Stop script after redirect | exit(); | Prevents further code execution |
| Relative URL redirect | header('Location: /page.php'); | Works if URL is correct |
| Check for output before header | Use output buffering or no output | Avoids header errors |
Key Takeaways
Always call header('Location: URL') before any output to redirect in PHP.
Use exit() immediately after header() to stop script execution.
Never send any output (echo, HTML) before calling header().
Use full URLs or correct relative paths in the Location header.
Check for errors about headers already sent to fix output issues.