Hardware FixRecommendedDevice not working? Your driver may be the problemCheck updates for common hardware issues.Fix DriversOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsPC HealthRecommendedCrashes, freezes, slowdowns? Check your PC nowSpot repairable issues before they interrupt work.Check PC×
Skip to content
World desk15 min

What is a PHP Header Redirect and How Can You Code One

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

A PHP header redirect sends a browser or client to a different URL by returning an HTTP response with a Location header. Instead of rendering the current page, the server instructs the client to request another address, making redirects useful for login flows, moved pages, form handling, access control, and canonical URL management.

In PHP, redirects are usually created with the header() function before any output is sent to the browser. The redirect can include an HTTP status code such as 301, 302, 303, or 307, depending on whether the move is permanent, temporary, or related to a form submission.

As an Amazon Associate I earn from qualifying purchases.

Correct redirect handling requires precise syntax, clean output control, and safe URL validation. Small mistakes such as sending whitespace before header(), forgetting to stop script execution, or redirecting to untrusted user input can cause broken behavior or security issues.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

What a PHP Header Redirect Does

A PHP header redirect tells the browser or another HTTP client to request a different URL instead of continuing with the current response. In practice, your PHP script sends an HTTP response header named Location, and the client follows that address by making a new request. The original page does not “move” the user with JavaScript or render a link for them to click; it instructs the client at the HTTP protocol level that the next destination is somewhere else.

#1 Best Overall
GameStop Physical Gift Card
  • Redeemable at US GameStop, EB Games, Babbage's, Electronic Boutique, EBX, Planet X, and Software Etc. stores. Also redeemable online at and GameStop.com and EBGames.com.
  • Over 6,100 stores located throughout the United States.
  • GameStop. Power to the Players.
  • Redemption: Instore and Online
  • No returns and no refunds on gift cards.

For example, after a user successfully logs in, a PHP application might redirect them from /login.php to /dashboard.php. After submitting a form, the application might redirect from /save-profile.php back to /profile.php so refreshing the page does not resubmit the form. Redirects are also used when content has moved, when users need to authenticate before viewing a protected page, or when an application wants to canonicalize URLs such as sending http://example.com to https://example.com.

What happens during the redirect

  1. The browser requests a PHP page, such as /account.php.
  2. The PHP script decides that the user should go somewhere else.
  3. The script sends a Location header, usually with a 3xx HTTP status code.
  4. The browser receives the response and makes a second request to the URL in the Location header.
  5. The destination page returns its own response, which the browser displays.

A header redirect is therefore not the final page content itself. It is a short HTTP response that points the client to another resource. A typical response might include a status such as 302 Found for a temporary redirect or 301 Moved Permanently for a permanent redirect, along with the destination URL. Search engines, browsers, API clients, and caching layers may treat those status codes differently, so the redirect communicates both the new address and the intended meaning of the move.

In PHP applications, header redirects are most useful before any output has been sent to the browser. That means the redirect decision usually happens near the top of a script, before HTML, whitespace, echoed text, or included templates produce output. This matters because HTTP headers must be sent before the response body. Once content has started streaming to the client, PHP may no longer be able to modify the headers, and the redirect can fail with a “headers already sent” warning.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Common use cases include access control, post-login navigation, logout flows, form handling, old-to-new URL migration, language or region routing, and enforcing HTTPS. A redirect can improve user experience and application structure when it sends users to the correct next page deliberately. It should not be used as a substitute for authorization checks, input validation, or proper routing; it is simply the HTTP mechanism for telling the client, “request this other URL now.”

How the PHP `header()` Function Works

PHP’s header() function sends a raw HTTP header from the server to the client before the response body is delivered. In the case of a redirect, it is most commonly used to send a Location header, which tells the browser or HTTP client to request a different URL. A typical redirect response does not move the user by changing HTML or JavaScript; it changes the HTTP response itself so the client receives instructions from the server.

The basic mechanism is straightforward: PHP prepares response headers, then the web server sends those headers along with the response body. When you call header('Location: /login.php'), PHP adds a Location header to the outgoing response. The browser sees that header, checks the response status code, and then performs a new request to the target address. If no status code is specified, PHP commonly sends a temporary redirect status such as 302 Found for a Location redirect.

Redirect headers and status codes

A Location header should normally be paired with an appropriate 3xx HTTP status code. The status code describes the type of redirect, while the Location value provides the destination. For example, a temporary redirect might use 302 or 307, while a permanent redirect might use 301 or 308. PHP lets you set the code directly in the header() call by passing it as the third argument.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
  • header('Location: /dashboard.php'); sends a redirect header using PHP’s default redirect behavior.
  • header('Location: /new-page.php', true, 301); sends a permanent redirect.
  • header('Location: /temporary-page.php', true, 302); sends a temporary redirect.

The second argument, true, tells PHP to replace a previously set header of the same type. This is the usual choice for redirects because a response should not send mulle conflicting Location headers. The third argument sets the HTTP response code. This makes the redirect clearer to browsers, search engines, APIs, and caching layers.

Headers must be sent before output

The header() function only works correctly if PHP has not already sent output to the client. Output can include visible HTML, whitespace before the opening <?php tag, accidental blank lines, echoed text, or error messages. Once output begins, the HTTP headers may already be committed, and PHP can no longer modify them. This is when developers often see the warning Cannot modify header information – headers already sent.

Rank #2
Xbox Physical Gift Card | $25
  • XBOX GIFT CARD: Buy full digital game downloads, game add-ons, in-game currency, memberships, devices, apps, movies, TV shows, and more.
  • DIGITAL GAMES: Choose from hundreds of games, from AAA to indie options. Start playing the moment your most anticipated game is available when you pre-order and pre-download it.
  • GAME AD-ONS: Extend the experience of your favorite games with add-ons and in-game currency.
  • MOVIES & TV SHOWS: Rent or buy new and popular movies and TV shows from a massive library.
  • PERFECT GIFT: Great as a gift for a friend or yourself. Xbox Gift Cards are easy to use, never expire, and give the freedom to pick the gift they want. Enjoy more ways to play without a credit card attached to your Microsoft account.

After sending a redirect header, execution does not automatically stop. PHP will continue running the rest of the script unless you explicitly terminate it. For that reason, redirects are commonly followed by exit; to prevent protected content, database changes, or additional output from being processed after the redirect instruction.

  • Call header() before echoing HTML or sending other output.
  • Use a valid absolute or root-relative destination URL.
  • Set a suitable 3xx status code for the redirect’s purpose.
  • Follow the redirect with exit; to stop further script execution.

Basic PHP Header Redirect Syntax

The simplest PHP header redirect sends a Location header to the browser and then stops the script. The target can be an absolute URL, such as https://example.com/login.php, or a relative path, such as /login.php. In most production applications, an absolute path from the site root is often clearer than a page-relative path because it avoids surprises when the same file is reached from different directories.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

A basic redirect looks like this:

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

The exit call is part of the standard pattern. After PHP sends the redirect header, the current script does not automatically stop running. Without exit, code below the redirect may still execute, which can cause unwanted database writes, session changes, email sends, or page output. Treat header('Location: ...') and exit as a pair unless there is a very specific reason not to.

Redirecting with a status code

By default, PHP commonly sends a temporary redirect for a Location header, but it is better to be explicit. The header() function accepts a third argument for the HTTP status code. For example, use 302 for a temporary redirect and 301 for a permanent redirect:

<?php
header('Location: /new-page.php', true, 302);
exit;
?>

For a permanent redirect:

<?php
header('Location: https://example.com/new-url', true, 301);
exit;
?>

The second argument, true, tells PHP to replace a previously set header with the same name. This is normally what you want for redirects, because sending mulle conflicting Location headers can create unpredictable behavior. If your application has already prepared headers earlier in the request, being explicit helps keep the response clear.

Using redirects after form handling

A common redirect pattern in PHP is Post/Redirect/Get. After processing a submitted form, the script redirects the user to a confirmation page or back to the form page with a success message stored in the session. This prevents duplicate submissions if the user refreshes the browser.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

<?php
session_start();

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// Save form data or perform an action here.

$_SESSION['message'] = 'Your changes were saved.';
header('Location: /account.php', true, 303);
exit;
}
?>

The 303 status code is useful after a successful form submission because it tells the browser to make the next request with GET. That makes it a good fit for redirecting users away from a POST endpoint after the server has finished processing their input.

Building a redirect target safely

If the redirect destination is fixed, hard-code it or derive it from trusted application routes. Be careful when accepting a redirect target from a query string, such as ?next=..., because attackers can abuse open redirects to send users to malicious sites. A safer approach is to allow only internal paths or compare the destination against an allowlist.

Rank #3
$100 XBOX Gift Card [Digital Code]
  • THE PERFECT GAMING GIFT — Buy an XBOX Gift Card for yourself or a friend and let them choose the games, add‑ons, subscriptions, and accessories they want most.
  • USE FOR GAMES & CONTENT — Redeem for thousands of digital XBOX games, from backward compatible classics to the latest new releases, plus DLC and in‑game currency.
  • GAME PASS READY — Apply your balance toward XBOX Game Pass Ultimate to play new titles on day one* and access a library of hundreds of high‑quality console games.
  • PRE‑ORDER & PRE‑INSTALL GAMES — Use your balance to pre‑order and pre‑download upcoming titles so you’re ready to play the moment they launch.
  • NO FEES OR EXPIRATION — XBOX Gift Cards never expire and have no service fees, so your balance is ready whenever you are.

<?php
$allowedTargets = ['/dashboard.php', '/profile.php', '/settings.php'];
$target = $_GET['next'] ?? '/dashboard.php';

if (!in_array($target, $allowedTargets, true)) {
$target = '/dashboard.php';
}

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

header('Location: ' . $target, true, 302);
exit;
?>

Redirect syntax is short, but placement matters. Call header() before any HTML, whitespace, echoed content, or accidental output from included files. Once PHP has started sending the response body, it may be too late to modify headers, and the redirect can fail with a “headers already sent” warning.

Choosing the Right HTTP Redirect Status Code

When you send a redirect with PHP’s header() function, the Location header tells the browser where to go next, while the HTTP status code tells the browser, search engine, or API client how to interpret that move. If you do not specify a status code, PHP commonly sends a temporary redirect response, often 302 Found. That may work in a browser, but it can be misleading when the redirect is meant to be permanent, method-preserving, or related to a form submission.

The status code is passed as the third argument to header(). For example, a permanent redirect can be sent with header('Location: https://example.com/new-page', true, 301);. The second argument, true, means the header should replace any previous header of the same type. After sending the redirect, your script should normally call exit; so PHP does not continue executing protected actions, rendering old content, or sending additional output.

Common redirect status codes in PHP

Status code Name Common use
301 Moved Permanently Use when a URL has permanently changed, such as after a site migration or canonical URL cleanup.
302 Found Use for temporary redirects where the original URL may be used again.
303 See Other Use after a successful form submission to redirect the browser to a confirmation page using a GET request.
307 Temporary Redirect Use for temporary redirects where the HTTP method and request body should be preserved.
308 Permanent Redirect Use for permanent redirects where the HTTP method and request body should be preserved.

For standard page redirects, 301 and 302 are the most common choices. A 301 is appropriate when an old article URL, product URL, or entire domain has permanently moved. Search engines may transfer ranking signals to the new URL and browsers may cache the redirect aggressively. Because of that caching behavior, avoid using 301 while testing unless you are certain the redirect is final. A 302 is better for temporary maintenance pages, short-term campaign routing, A/B tests, or login redirects where the destination may change later.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

For form handling, 303 See Other is often the safest choice after processing a POST request. It supports the Post/Redirect/Get pattern: the user submits a form, PHP processes it, and the browser is redirected to a result page with a GET request. This prevents accidental duplicate submissions if the user refreshes the page. For APIs and non-browser clients, 307 and 308 are useful because they preserve the original request method. If a client sends a POST request and receives a 307, it should repeat the POST request at the new URL instead of changing it to GET.

Choose the code based on whether the move is permanent, whether the request method should change, and how clients should cache the response. A clear choice avoids SEO problems, stale browser caches, repeated form submissions, and unexpected behavior in API integrations.

Common Errors When Coding PHP Redirects

PHP redirects are simple to write, but they are also easy to break because HTTP headers must be sent before the response body. A redirect can fail silently in some environments, display a warning in others, or behave inconsistently if output, status codes, or user input are handled incorrectly. Most redirect bugs come from sending content too early, forgetting to stop script execution, or building unsafe destination URLs.

Sending Output Before Calling header()

The most common error is producing any output before the redirect header is sent. This includes visible HTML, whitespace outside PHP tags, blank lines before an opening <?php tag, echo statements, debug output, accidental UTF-8 byte order marks, or warnings generated by PHP itself. Once PHP starts sending the response body, headers may already be committed, which prevents header('Location: ...') from modifying them.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #4
Fortnite Physical Gift Card | Powered by the Epic Games Store - $50
  • An Epic Games account is required to redeem an Epic Games Store Card code
  • If playing on a console platform (PlayStation Network, Xbox Live, Nintendo Switch or Mobile) you need to link your Epic Games account to that gaming platform (one time) to redeem your gift card code
  • The 16 digit code on the back of the card WILL NOT work if redeemed directly through your gaming platform (PlayStation Network, Xbox Live, Nintendo Switch, Mobile, etc.)
  • Note: Nintendo devices do not support Fortnite Shared Wallet, so V-Bucks purchased using your account balance will not show up on your Nintendo device. However, if you purchase items in the web Item Shop — or another platform where you play Fortnite — those items will be available in your Locker across all platforms.
  • Redemption: Online
  • Incorrect: printing text, HTML, or debug data before the redirect.
  • Correct: run redirect checks before rendering templates or sending output.
  • Helpful check: use headers_sent() while debugging to find whether output has already started.

Another frequent mistake is forgetting to call exit or die after the redirect. The header() function only sends an HTTP header; it does not automatically stop PHP from executing the rest of the script. Without an immediate termination, later code may update records, render protected content, overwrite headers, or trigger errors after the browser has already been instructed to leave the page.

Incorrect Location Values and Status Codes

A redirect header must be correctly formatted. The header name is Location, followed by a colon and a valid target path or URL. Misspelling the header, omitting the colon, adding unsupported characters, or passing unsanitized input can cause broken redirects or security issues. Relative paths such as /login.php are commonly accepted by modern clients, while absolute URLs such as https://example.com/login.php are useful for cross-domain redirects or canonical host changes.

  • Wrong header name: header('Redirect: /login.php') will not perform a standard HTTP redirect.
  • Missing termination: header('Location: /dashboard.php') should usually be followed by exit;.
  • Wrong status code: using 301 for temporary login or form redirects can cause browsers and search engines to cache the wrong behavior.
  • Unsafe destination: redirecting to a raw $_GET['next'] value can create an open redirect vulnerability.

Status code mistakes can be especially damaging. A permanent 301 or 308 redirect may be cached aggressively, so it should not be used for temporary application flow such as redirecting unauthenticated users to a login page. For most short-term navigation, 302 or 303 is safer. After a successful POST request, 303 See Other is often the right choice because it tells the client to load the next page with a GET request, reducing duplicate form submissions.

Redirect Loops and Unsafe User-Controlled Redirects

Redirect loops happen when the destination page triggers the same redirect condition again. For example, a login page that checks for an unauthenticated user and redirects to itself can trap the browser in an endless cycle. Always exclude the target route from the condition or check the current path before redirecting. When using a return URL, validate it against an allowlist or restrict it to local paths that begin with a single forward slash. Do not redirect blindly to external URLs supplied by a query string, form field, or referrer header.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Best Practices for Safe and Reliable Redirects

A safe PHP header redirect does more than send a Location header. It must run before any output, use the correct destination, stop script execution, and avoid sending users to untrusted URLs. In production applications, redirects often sit on sensitive paths such as login handlers, checkout flows, password reset pages, and admin panels, so small mistakes can create broken navigation or security issues.

Validate the redirect destination

If a redirect target comes from user input, such as a next, return, or redirect query parameter, validate it before passing it to header(). Unchecked external URLs can lead to open redirect vulnerabilities, where an attacker uses your trusted domain to forward users to a phishing page. A common safer pattern is to allow only relative paths within your own application, or to compare the host against a small allowlist of approved domains.

  • Prefer internal paths such as /dashboard instead of full user-supplied URLs.
  • Reject protocol-relative URLs such as //example.com unless explicitly allowed.
  • Normalize and check paths before redirecting to avoid unexpected destinations.
  • Use an allowlist when external redirects are required for payment providers or single sign-on flows.

Stop execution after the redirect

After calling header('Location: ...'), call exit; immediately. The browser is expected to request the new URL, but PHP will continue running the current script unless you stop it. Without exit;, the script might update records, render protected content, send emails, or perform other actions after the redirect header has already been queued.

A reliable redirect should also set an explicit status code. For example, use 302 or 303 after a form submission when the redirect is temporary, and use 301 only when the old URL has permanently moved. For authentication flows, 302 is usually appropriate because the destination depends on the current session state. For POST-redirect-GET patterns, 303 See Other clearly tells the client to fetch the next page with a GET request.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Keep redirects predictable

Build redirect in one place where possible, especially in larger PHP applications. A small helper function can enforce validation, set the status code, send the header, and exit consistently. This reduces repeated code and prevents one controller from forgetting a safety check. It also makes redirects easier to audit when routes change or when security reviews are performed.

Best Value
$25 PlayStation Store Gift Card [Digital Code]
  • Redeem for anything on PlayStationStore: games, add-ons, PlayStationPlus and more.
  • Everything you want to play. Choose from the largest library of PlayStation content.
  • Use gift card funds to contribute towards PlayStationPlus memberships.
Practice Benefit
Send headers before output Prevents “headers already sent” failures.
Use exit; after header() Stops unintended code from running.
Validate user-controlled destinations Reduces open redirect risk.
Choose the correct status code Improves browser, cache, and search engine behavior.

Finally, test redirects under realistic conditions: with sessions enabled, behind your web server or reverse proxy, and with both successful and failed form submissions. Check the response in browser developer tools or with an HTTP client to confirm the Location value and status code. A redirect that works in a simple local script can behave differently once output buffering, middleware, cookies, caching, or HTTPS enforcement are involved.

Frequently Asked Questions

Do I have to call exit after a PHP header redirect?

Yes, you should usually call exit; immediately after sending a redirect with header('Location: ...');. The redirect header tells the browser to request another URL, but PHP may continue running the rest of the script unless you stop it. This can cause unwanted database writes, output, or security issues.

Why am I getting “headers already sent” when using header()?

This error means PHP already sent output to the browser before your header() call. Common causes include whitespace before <?php, accidental echo statements, HTML output, or UTF-8 BOM characters in included files. Move the redirect before any output, remove stray whitespace, or use output buffering if needed.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Which status code should I use for a PHP redirect?

Use 302 or 303 for temporary redirects, such as sending a user to a login page or redirecting after a form submission. Use 301 only when a URL has permanently moved, because browsers and search engines may cache it aggressively. For preserving the original request method, use 307 or 308 instead of 302 or 301.

Can I redirect to another website with PHP header()?

Yes, you can redirect to an absolute external URL, such as header('Location: https://example.com');. If the destination comes from user input, validate it carefully to avoid open redirect vulnerabilities. A safer approach is to allow only known domains or redirect using internal path values you control.

Can I use a relative URL in a PHP Location header?

Modern clients generally support relative URLs in the Location header, such as header('Location: /dashboard');. For broad compatibility and clearer behavior, absolute paths from the site root are usually better than relative paths like ../page.php. If you are redirecting across domains or protocols, use a full absolute URL.

Bottom Line

A PHP header redirect uses the header() function to send a Location response before any output reaches the browser, making it a simple and effective way to move users to another URL. Use the right status code, call exit immediately after the redirect, and avoid common issues like whitespace, prior output, or unvalidated user-controlled URLs.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

For your next implementation, choose the redirect type that matches your use case, test it with browser developer tools or curl, and keep security in mind when redirecting based on request data. Done carefully, PHP redirects are reliable tools for login flows, moved pages, form handling, and application routing.

Quick Recap

Bestseller No. 1
GameStop Physical Gift Card
GameStop Physical Gift Card
Over 6,100 stores located throughout the United States.; GameStop. Power to the Players.; Redemption: Instore and Online
$25.00
Bestseller No. 2
Xbox Physical Gift Card | $25
Xbox Physical Gift Card | $25
MOVIES & TV SHOWS: Rent or buy new and popular movies and TV shows from a massive library.
$25.00
Bestseller No. 3
$100 XBOX Gift Card [Digital Code]
$100 XBOX Gift Card [Digital Code]
Gift cards are region‑specific (U.S. only) and cannot be transferred once redeemed.
$100.00
Bestseller No. 4
Fortnite Physical Gift Card | Powered by the Epic Games Store - $50
Fortnite Physical Gift Card | Powered by the Epic Games Store - $50
An Epic Games account is required to redeem an Epic Games Store Card code; Redemption: Online
$50.00
Bestseller No. 5
$25 PlayStation Store Gift Card [Digital Code]
$25 PlayStation Store Gift Card [Digital Code]
Redeem for anything on PlayStationStore: games, add-ons, PlayStationPlus and more.; Everything you want to play. Choose from the largest library of PlayStation content.
$25.00

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Crashes, No Sound, or Screen Glitches?Free driver scan
PC Slower Than It Used to Be?Free scan - under a minute

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.