phpregexhttp-redirectipreferer

PHP redirect based on IP AND referrer


I'm trying to redirect users within my network to a specific landing page on our website based on their IP and a blank referrer. This code works, but it ends up in a redirect loop. How do I break out of the redirect loop to correctly redirect a user? Thanks!

$visitor = $_SERVER['HTTP_REFERER'];
$clientip = $_SERVER['REMOTE_ADDR'];
$ip = a regex list of IPs;
if (empty($visitor))
{
    if (preg_match($ip, $clientip)) {
        header('Location: http://example.com');
            die();
            } 
}

Solution

  • Add a session to that user that you know that they were redirected already:

    session_start();
    $visitor = $_SERVER['HTTP_REFERER'];
    $clientip = $_SERVER['REMOTE_ADDR'];
    $ip = a regex list of IPs;
    if (empty($visitor))
    {
    
        //add on if they did not redirect yet.
        if (preg_match($ip, $clientip) && 
            (!isset($_SESSION['redirect']) || !$_SESSION['redirect'])) {
            $_SESSION['redirect'] = true;
            header('Location: http://example.com');
            die();
        } 
    
    }