Question
Is it possible to redirect a user to a different page using PHP?
For example, if a user visits www.example.com/page.php, I want to send them to www.example.com/index.php without using a meta refresh. How can I do that in PHP?
I also want to understand whether this approach can be used to protect pages from unauthorized users.
Short Answer
By the end of this page, you will understand how PHP redirects work using the header() function, when to call it, why exit is usually added after it, and how redirects are commonly used for login protection, validation, and flow control in real applications.
Concept
PHP can tell the browser to go to a different URL by sending an HTTP response header. The most common way to do this is with the header() function.
A redirect happens on the server before the browser finishes loading the current page. Instead of rendering the current page, the server responds with a Location header, and the browser then requests the new page.
Basic example:
<?php
header('Location: /index.php');
exit;
This matters because redirects are a standard part of web development. They are used to:
- send users to a login page if they are not authenticated
- move users after form submission
- route old URLs to new ones
- prevent access to restricted pages
- guide users through multi-step processes
For page protection, a redirect is often combined with authentication checks. For example, if a user is not logged in, your PHP code can redirect them to a login page before any protected content is shown.
One important rule: header() must be called before any output is sent to the browser. That means no HTML, no echo, and ideally no stray whitespace before <?php if you want the redirect to work reliably.
Mental Model
Think of PHP as a receptionist at a building entrance.
- The visitor asks for
page.php - Before letting them in, the receptionist checks the rules
- If the visitor should not enter, the receptionist says: "Go to
index.phpinstead" - The visitor then walks to that new location
The key idea is that PHP does not physically move the user. It sends instructions to the browser telling it where to go next.
Syntax and Examples
Basic syntax
<?php
header('Location: /index.php');
exit;
What this does
header('Location: /index.php');sends an HTTP redirect headerexit;stops the script immediately so no extra code runs
Redirect to another page on the same site
<?php
header('Location: /index.php');
exit;
Using /index.php is usually better than hardcoding the full domain if the redirect stays on the same site.
Redirect to a full URL
<?php
header('Location: https://www.example.com/index.php');
exit;
Redirect unauthorized users
<?php
session_start();
if (!isset($_SESSION['user_id'])) {
header('Location: /login.php');
exit;
}
This is a very common pattern. If the session does not contain a logged-in user, the script redirects to the login page.
Redirect after a form submission
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// Save form data here
header('Location: /thank-you.php');
exit;
}
This avoids re-submitting the form if the user refreshes the page.
Redirect with a status code
<?php
header('Location: /index.php', true, 302);
exit;
Common redirect status codes:
302: temporary redirect301: permanent redirect303: often used after form submission307and308: preserve request method in stricter cases
Step by Step Execution
Consider this example:
<?php
session_start();
if (!isset($_SESSION['user_id'])) {
header('Location: /login.php');
exit;
}
echo 'Welcome to the protected page';
Step-by-step
-
session_start();begins access to session data. -
if (!isset($_SESSION['user_id']))checks whether the user is logged in. -
If
user_idis missing, PHP runs:header('Location: /login.php');This sends a redirect instruction to the browser.
-
exit;stops the script. Theecholine below will not run. -
The browser receives the redirect response and requests
/login.php. -
If
user_iddoes exist, theifblock is skipped. -
The browser stays on the current page and sees:
Welcome to the protected page
This is why redirects are useful for access control: you can decide early whether the user is allowed to continue.
Real World Use Cases
Common practical uses
Protecting private pages
If a user tries to open an admin page without being logged in, redirect them to /login.php.
Redirecting after login
Once login succeeds, redirect the user to their dashboard:
header('Location: /dashboard.php');
exit;
Redirecting after logout
After destroying the session, send the user back to the homepage or login screen.
Preventing duplicate form submissions
After saving a form, redirect to a success page or back to the form with a message.
Replacing old URLs
If a page has moved, redirect old traffic to the new URL.
Role-based access
Send admins to /admin.php and regular users to /profile.php based on permissions.
Real Codebase Usage
In real PHP applications, redirects are usually part of request handling and access control.
Common patterns
Guard clauses
Developers often redirect early and stop the script immediately:
<?php
session_start();
if (!isset($_SESSION['user_id'])) {
header('Location: /login.php');
exit;
}
This keeps the code simple and avoids nesting everything inside large if blocks.
Validation failures
If submitted data is invalid, redirect back to the form:
<?php
if (empty($_POST['email'])) {
header('Location: /register.php');
exit;
}
Post/Redirect/Get pattern
A very common practice after handling a POST request:
- User submits a form
- Server processes the data
- Server redirects to another page
- Browser loads the new page with a GET request
This reduces accidental duplicate submissions.
Central authentication checks
In larger codebases, authentication logic is often reused through helper functions or middleware-like structures:
<?php
function requireLogin(): void
{
session_start();
if (!isset($_SESSION['user_id'])) {
header('Location: /login.php');
exit;
}
}
Then protected pages can call requireLogin(); at the top.
Error handling and fallback navigation
If a resource is missing or a condition fails, developers may redirect to a safer page instead of showing a broken experience.
Common Mistakes
1. Sending output before header()
This is the most common mistake.
Broken code
<?php
echo 'Hello';
header('Location: /index.php');
exit;
This may cause a "headers already sent" warning because output was sent before the redirect header.
Fix
<?php
header('Location: /index.php');
exit;
2. Forgetting exit
Risky code
<?php
header('Location: /index.php');
echo 'This may still run';
Even if the browser is redirected, the script may continue executing on the server.
Better
<?php
header('Location: /index.php');
exit;
3. Assuming redirect means security by itself
Redirecting unauthorized users is useful, but the real protection comes from checking permissions on the server.
Wrong mindset
- "If I redirect them, the page is secure"
Correct mindset
- Always verify authentication and authorization before sending protected content
- Redirect is just the response to a failed check
4. Using relative paths carelessly
This can work differently depending on your setup.
Less clear
header('Location: index.php');
Usually clearer
header('Location: /index.php');
5. Forgetting session_start() when checking login state
Broken code
<?php
if (!isset($_SESSION['user_id'])) {
header('Location: /login.php');
exit;
}
Fix
<?php
session_start();
if (!isset($_SESSION['user_id'])) {
header('Location: /login.php');
exit;
}
Comparisons
Redirect methods compared
| Method | How it works | Recommended? | Notes |
|---|---|---|---|
header('Location: ...') | Sends an HTTP redirect header | Yes | Standard PHP server-side redirect |
| Meta refresh | Browser reads HTML and redirects later | Usually no | Slower and less reliable for control flow |
| JavaScript redirect | Client-side script changes window.location | Sometimes | Useful only when JavaScript is required |
| Include another PHP file | Runs another file on the server | No | This is not a redirect; URL stays the same |
header() with common status codes
| Status code | Meaning | Typical use |
|---|---|---|
301 | Permanent redirect | Old URL permanently moved |
302 | Temporary redirect | Default common redirect |
303 | See Other | Redirect after POST form submission |
307 | Temporary redirect preserving method | More strict temporary redirect |
308 | Permanent redirect preserving method | More strict permanent redirect |
Redirect vs include
| Action | Browser URL changes? | New request? |
|---|---|---|
| Redirect | Yes | Yes |
include / require | No | No |
If you want the user to go to another page, use a redirect. If you want to reuse code from another file on the server, use include or require.
Cheat Sheet
header('Location: /index.php');
exit;
Rules
- Call
header()before any output - Usually call
exit;right after redirecting - Use
/pathfor same-site redirects when possible - Use full URLs when redirecting to another domain
- Start the session with
session_start()before checking$_SESSION
Common patterns
Redirect if not logged in
session_start();
if (!isset($_SESSION['user_id'])) {
header('Location: /login.php');
exit;
}
Redirect after form submit
header('Location: /thank-you.php');
exit;
Permanent redirect
header('Location: /new-page.php', true, 301);
exit;
Common error
echo 'Output first';
header('Location: /index.php'); // headers already sent
Remember
A redirect can help control access flow, but the real security comes from server-side permission checks.
FAQ
Can PHP redirect to another page without a meta refresh?
Yes. The standard way is to use header('Location: /some-page.php'); before any output is sent.
Why does header() sometimes not work in PHP?
Usually because output was sent before calling header(). Even whitespace before <?php can cause problems in some cases.
Should I use exit after header('Location: ...')?
Yes, in most cases. It stops the script so no extra code runs after the redirect.
Can I use PHP redirects to protect private pages?
Yes, but only if you first check authentication or authorization on the server. The redirect is the result of that check.
What is the difference between a redirect and include in PHP?
A redirect tells the browser to request a different URL. include runs another PHP file inside the current request and keeps the same URL.
Can I redirect to an external website with PHP?
Yes.
header('Location: https://example.org');
exit;
Which redirect status code should I use?
Use 302 for temporary redirects in most simple cases. Use 301 if the move is permanent. Use 303 after a POST when you want the next request to be a GET.
Mini Project
Description
Build a small PHP page protection example for a members-only page. This project demonstrates how redirects are used in practice to block unauthorized access and send users to a login page.
Goal
Create a protected page that only logged-in users can access, and redirect everyone else to a login page.
Requirements
- Start a PHP session before checking login data.
- Treat
$_SESSION['user_id']as the sign that a user is logged in. - Redirect users without
user_idto/login.php. - Stop script execution immediately after redirecting.
- Show protected content only to logged-in users.
Keep learning
Related questions
Are PDO Prepared Statements Enough to Prevent SQL Injection in PHP?
Learn how PDO prepared statements prevent SQL injection in PHP, what they protect, and the mistakes that still leave MySQL apps vulnerable.
Can You Bind an Array to an IN Clause in PHP PDO?
Learn how PDO handles placeholders in IN() clauses, why arrays cannot be bound directly, and the safe PHP pattern to build dynamic queries.
Choosing the Right MySQL Collation for PHP and UTF-8
Learn how MySQL character sets and collations work with PHP, and how to choose a practical UTF-8 setup for web applications.