How to redirect to another page using PHP

How to redirect to another page using PHP

  1. Blog
  2. 15 November 2026
  3. 2 min read

Stefan Bogdanescu

Founder & Senior Architect

Handling Redirects After Outputting HTML in PHP

You are running into a classic constraint of HTTP: once any character is sent to the browser, the connection is considered "live." You cannot send a Location header or an empty response body afterward. Since your login form renders its HTML before checking if the credentials were valid, you have already flushed the output buffer when the user clicks "Login." At that point, calling header("Location: profile.php") will simply fail, and the browser will display your original form page instead of redirecting.

To solve this, you need to intercept the request before any HTML is printed. The standard approach involves checking if the form has been submitted first. If it has, perform the authentication logic and redirect immediately. Only if the authentication fails or the user hasn't submitted the form should you render the HTML view.

Here is how you can refactor login.php to handle this flow correctly. You start by starting a session, which is essential for storing user data like the logged-in username. Then, check if the request method is POST. If it is, execute your database logic. Crucially, once you have verified the credentials and set the session variable, you must send the redirect header and then exit the script immediately.

<?php 
session_start(); 

// Check if the form was submitted
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $username = $_POST["username"];
    $password = $_POST["password"];

    // Database configuration
    $dbhost = "localhost";
    $dbuser = "root";
    $dbpass = "root";
    
    $conn = mysql_connect($dbhost, $dbuser, $dbpass) or die("Error connecting to database");
    mysql_select_db("database", $conn);

    // Note: Using prepared statements is highly recommended to prevent SQL injection.
    // The original code mixes user input directly into the query string, which is a security risk.
    
    $query = "SELECT username FROM users WHERE username = '$username' AND password = '$password'";
    $result = mysql_query($query) or die("Failed Query");

    if ($result && $row = mysql_fetch_assoc($result)) {
        $_SESSION["user"] = $row['username'];

        // Redirect immediately after success
        header("Location: profile.php");
        exit(); 
    } else {
        // Authentication failed. Now it is safe to output HTML because we didn't redirect.
        // You would typically show an error message here.
        echo "Invalid credentials.";
    }
} 
// If we reach this point, the form was not submitted (GET request) or validation logic needs handling.

echo "<!DOCTYPE html> 
  <html> 
     <head> 
        <meta charset='utf-8'> 
        <title>Sprout</title>
    </link rel='stylesheet' href='stylesheet.css' type='text/css'>
     </head>
 <body>
    <div class='box'>
    <form action='login.php' method='post'>
       Name<br /> <input type='text' name='username' class='form'/>
       Password<br /> <input type='password' name='password' class='form'/>
       <input type='submit' value='Login' class='button' />
    </form>
    </div>
 </body>
  </html>";
?>

The key takeaway here is the order of operations. The exit() function is mandatory after the header() call to ensure no further code (like the HTML echo at the bottom) runs. Without exit(), PHP would continue executing and output the form HTML anyway, resulting in a confusing page that shows both the login form and a 302 redirect status line in the network tab.

Beyond this immediate fix, it is worth noting significant security vulnerabilities in your current implementation. You are using the deprecated mysql_* functions and constructing SQL queries with string concatenation. This makes your application susceptible to SQL injection attacks. If a user inputs ' OR '1'='1 into the username field, your query will bypass password checks entirely.

In modern PHP development, you should switch to MySQLi or PDO with prepared statements. Prepared statements separate the SQL logic from the data, ensuring that user input is treated strictly as data, never as executable code. Furthermore, storing passwords in plain text is a critical risk; passwords should always be hashed using algorithms like bcrypt before being stored in the database.

If you are starting a new project or looking to streamline this authentication logic without writing raw SQL and session management from scratch, frameworks like Laravel offer robust helpers. The ecosystem around https://laravelcompany.com provides resources on how to implement secure login flows that handle redirects automatically within the framework's request lifecycle, abstracting away the manual header checks you are currently managing.

Our network