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[])) {
();
;
}
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 does exist, the block is skipped.
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
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');
;
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
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
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?
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
Converting HTML and CSS to PDF in PHP: Core Concepts, Limits, and Practical Approaches
Learn how HTML-to-PDF conversion works in PHP, why CSS support varies, and how to choose practical approaches for reliable PDF output.
How PHP foreach Actually Works with Arrays
Learn how PHP foreach works internally, including array copies, internal pointers, by-value vs by-reference behavior, and common pitfalls.
How to Check String Prefixes and Suffixes in PHP
Learn how to check whether a string starts or ends with specific text in PHP using simple functions and practical examples.