Question

How to Redirect in PHP with the header() Function

phphttp-redirecthttp-status-code-301

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.php instead"
  • 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.

Take Quiz

Syntax and Examples

Basic syntax

<?php
header('Location: /index.php');
exit;

What this does

  • header('Location: /index.php'); sends an HTTP redirect header
  • exit; 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 redirect
  • 301: permanent redirect
  • 303: often used after form submission
  • 307 and 308: 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

  1. session_start(); begins access to session data.

  2. if (!isset($_SESSION['user_id'])) checks whether the user is logged in.

  3. If user_id is missing, PHP runs:

    header('Location: /login.php');
    

    This sends a redirect instruction to the browser.

  4. exit; stops the script. The echo line below will not run.

  5. The browser receives the redirect response and requests /login.php.

  6. If user_id does exist, the if block is skipped.

  7. 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.

Take Quiz

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:

  1. User submits a form
  2. Server processes the data
  3. Server redirects to another page
  4. 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

MethodHow it worksRecommended?Notes
header('Location: ...')Sends an HTTP redirect headerYesStandard PHP server-side redirect
Meta refreshBrowser reads HTML and redirects laterUsually noSlower and less reliable for control flow
JavaScript redirectClient-side script changes window.locationSometimesUseful only when JavaScript is required
Include another PHP fileRuns another file on the serverNoThis is not a redirect; URL stays the same

header() with common status codes

Status codeMeaningTypical use
301Permanent redirectOld URL permanently moved
302Temporary redirectDefault common redirect
303See OtherRedirect after POST form submission
307Temporary redirect preserving methodMore strict temporary redirect
308Permanent redirect preserving methodMore strict permanent redirect

Redirect vs include

ActionBrowser URL changes?New request?
RedirectYesYes
include / requireNoNo

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.

Take Quiz

Cheat Sheet

header('Location: /index.php');
exit;

Rules

  • Call header() before any output
  • Usually call exit; right after redirecting
  • Use /path for 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.

Take Quiz

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

  1. Start a PHP session before checking login data.
  2. Treat $_SESSION['user_id'] as the sign that a user is logged in.
  3. Redirect users without user_id to /login.php.
  4. Stop script execution immediately after redirecting.
  5. Show protected content only to logged-in users.
Take Quiz

Keep learning

Related questions

View more