Search

Redirecting a Page Using PHP

0 views

How to Redirect a Page in PHP

Redirecting a visitor to another URL with PHP is straightforward once you understand the role of the header() function. This function sends raw HTTP headers to the browser, and if the Location header is present, the browser navigates to the specified address. The trick is to call header() before any output is sent, otherwise PHP throws a “headers already sent” warning. In this guide we’ll walk through simple, dynamic, and conditional redirects, show how to avoid common pitfalls, and explain why the exit statement is often necessary afterward.

Before you write any code, place the redirect logic at the very top of your script, or wrap it inside a function that runs before any echo or HTML output. If you already have a layout that starts outputting content early, consider turning on output buffering with ob_start() at the very beginning. Buffering holds the output in memory until you call ob_end_flush(), giving your script time to send the header.

Here is the simplest example that points a user to a fixed destination:

Prompt
<?php</p> <p>header('Location: https://www.example.com/');</p> <p>exit;</p> <p>?>

The exit after the header guarantees that no further PHP code runs, preventing accidental output or logic that might interfere with the redirect. While some developers omit exit because the script ends anyway, leaving it in practice makes the intent crystal clear and stops any stray echo statements from reaching the browser.

When you need to build the redirect URL on the fly, store the base domain and query parameters in variables, concatenate them, and pass the result to header(). This technique is handy for search engines or third‑party services that require dynamic query strings:

Prompt
<?php</p> <p>$base = 'https://www.google.com/search?q=';</p> <p>$search = urlencode('Vinu Thomas');</p> <p>$url = $base . $search;</p> <p>header('Location: ' . $url);</p> <p>exit;</p> <p>?>

Using urlencode() ensures that special characters such as spaces or punctuation are correctly encoded. Skipping this step can cause broken URLs and a poor user experience. For instance, searching for “Vinu Thomas” without encoding would send “Vinu Thomas” literally, leading to a 404 or search engine error.

Conditional redirects are common when handling user roles, session status, or feature flags. For example, only admins should see the admin dashboard; regular users should be sent to the login page. The logic is straightforward:

Prompt
<?php</p> <p>session_start();</p> <p>$userRole = $_SESSION['role'] ?? 'guest';</p> <p>if ($userRole === 'admin') {</p> <p> header('Location: admin.php');</p> <p>} else {</p> <p> header('Location: login.php');</p> <p>}</p> <p>exit;</p> <p>?>

Notice the null coalescing operator (??) that sets a default value if the session variable is missing. This guards against undefined index notices and ensures a predictable redirect path. Always validate the session data before using it in a header call; otherwise, a malformed session could redirect a user to an unintended page.

Another pitfall occurs when you mix PHP with HTML without realizing that the very first byte of output (even a single whitespace) triggers the header error. Keep your redirect code inside tags, before any <html> or <body> tags. If you need to embed a redirect in a larger template, place the logic in a separate file included at the very top, or use a controller layer that decides the next route before rendering views.

To help developers debug header issues, turn on error reporting during development:

Prompt
<?php</p> <p>ini_set('display_errors', 1);</p> <p>error_reporting(E_ALL);</p> <p>?>

When you run the script, any “headers already sent” warning will surface, pinpointing the line where output started. Once you’ve confirmed that your redirects work, you can switch display_errors off for production to keep the user experience clean.

Beyond basic redirects, PHP’s header() can handle HTTP status codes. When you send a Location header, the default status is 302 (temporary). If you need to signal a permanent move, add the status explicitly:

Prompt
<?php</p> <p>header('Location: https://www.example.com/', true, 301);</p> <p>exit;</p> <p>?>

Search engines treat 301 redirects differently from 302, affecting SEO rankings. Use 301 only when the destination URL will replace the original permanently. For temporary redirects - like a maintenance notice - stick with 302.

Finally, for anyone needing deeper reference, the official PHP manual explains header() in detail. It covers usage constraints, available headers, and best practices for sending custom headers alongside redirects. The manual is a reliable source for keeping your knowledge up to date with the latest PHP releases.

For additional insights, consult

Suggest a Correction

Found an error or have a suggestion? Let us know and we'll review it.

Share this article

Comments (0)

Please sign in to leave a comment.

No comments yet. Be the first to comment!

Related Articles