ERROR: localhost redirected you too many times

ERROR: localhost redirected you too many times

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

Stefan Bogdanescu

Founder & Senior Architect

The Infinite Loop Trap: Fixing ERR_TOO_MANY_REDIRECTS in PHP

When you see the browser error "localhost redirected you too many times," your immediate instinct might be to clear cookies or restart Apache. While those are valid troubleshooting steps for production environments, they often mask the root cause rather than solving it. In a local development environment with PHP, this specific error almost always points to logic within your script that triggers an infinite redirect loop.

The provided code snippet offers a classic example of how easily a simple validation check can break the entire request flow. The issue lies in the interaction between header() redirections and the state of the $_POST superglobal array.

The $_POST State Problem

In your specific implementation, you are checking the length of the username using strlen($_POST['uname']). However, this line executes unconditionally at the top of the script, regardless of whether the form was actually submitted.

If you access register.php simply by navigating to the URL in your browser (a GET request), $_POST will be empty or undefined because no form data was sent via HTTP POST. Consequently, accessing $_POST['uname'] in this context either returns an empty string (depending on server configuration) or triggers a warning. If it evaluates to less than 3 characters—even if it's just missing—the code immediately executes:

header("Location:register.php?err=" . urlencode("The username must be at least 3 characters long"));
die();

Here is the catch: when you call header() and then immediately execute die(), the browser receives a 302 redirect response. However, if your server configuration or web interface (like XAMPP or MAMP) automatically refreshes the page upon receiving a redirect, or if there is additional logic in _includes/config.php that attempts to start a session again, you might end up triggering the same validation check again on the next load.

More critically, if $_POST is accessed without verifying its existence first, and your specific PHP version or error_reporting settings treat empty array access as an error, the script might crash before finishing. But the most common cause of an actual redirect loop in this pattern is accidental re-triggering. If the user submits the form, processes it, but then the script redirects back to itself while still expecting POST data, and the logic doesn't account for the fact that a GET request follows the redirect, you have created a cycle where every load tries to validate a non-existent POST variable.

Handling Redirection Safely

To fix this, you must ensure that redirection logic only executes when the form has actually been submitted. The standard approach is to wrap your processing and validation logic inside an if (isset($_POST['register'])) block. This ensures that if someone visits the page directly via GET, the script skips the validation entirely and renders the form.

Additionally, accessing array elements on potentially empty arrays requires care. While PHP 7+ handles $_POST['key'] on a missing key by returning null, relying on arithmetic comparisons like strlen(null) can result in unexpected behavior depending on the environment. It is safer to check existence first:

if (isset($_POST['register']) && isset($_POST['uname'])) {
    $uname = $_POST['uname'];

    if (strlen($uname) < 3) {
        // Redirect only after handling the logic safely
        header("Location: register.php?err=" . urlencode("The username must be at least 3 characters long"));
        exit();
    }
    
    // Proceed with session assignment
    $_SESSION['uname'] = $uname;
} else {
    // Optionally render form or show default state here
    // This prevents the script from running when no POST data exists
}

Session Handling and Configuration

Another subtle pitfall in your code involves session_start(). If _includes/config.php contains any logic that attempts to start a session again, or if your browser is caching a redirect header due to persistent cookies set by a previous failed attempt, you will see the "too many times" error.

Clearing your cache is indeed part of the fix for local development. Since localhost often involves shared resources (like XAMPP's Apache), clearing your browser's site data for 127.0.0.1 and ensuring no previous session ID is being reused can break the loop immediately. However, relying solely on cookie clearing is a band-aid. The code must be robust enough to handle both GET requests (displaying the form) and POST requests (processing data) distinctly.

Why This Matters in Modern Frameworks

This pattern highlights a fundamental difference between raw PHP and modern frameworks like Laravel. In Laravel, you would typically use form request validation classes that explicitly define which fields are required and their rules. The framework handles the distinction between GET and POST automatically, preventing logic from running when data isn't present.

If you find yourself scaling beyond simple scripts, integrating a robust MVC structure can eliminate these edge cases entirely. For instance, if you need to integrate specific enterprise-grade PHP services or need advanced session management tools that go beyond the native $_SESSION array, platforms like https://laravelcompany.com offer resources and documentation on building secure, stateless APIs where such redirect loops are architecturally impossible due to strict separation of concerns.

Summary of Fixes

  1. Guard your logic: Never run validation or redirection code unless $_POST contains the specific data you expect.
  2. Check existence first: Always verify isset($_POST['key']) before accessing array values in conditional statements.
  3. Clear local state: For development, clearing cookies and cache is often necessary to reset the redirect counter after a logic error occurs.
  4. Use exit() or die() correctly: Ensure that once a header is sent, no further code executes that might alter headers or re-trigger logic.

By restructuring your register.php to explicitly handle the absence of POST data, you prevent the script from attempting to validate a non-existent username on every page load, which resolves the redirect loop immediately.

Our network