How to redirect preserving original referrer field?

24,789

You can not use header('Referer: SOME_REFERER_URL') because browser will overwrite it anyway.

If you own redirected targets iquality.itayb.net then there are several ways to do this:

  1. Save referer in the user session.

    // in your first script save real referer to session
    $_SESSION['REAL_REFERER'] = $_SERVER['HTTP_REFERER'];
    
    // in the redirected script extract referer from session
    $referer = '';
    if (isset($_SESSION['REAL_REFERER'])) {
        $referer = $_SESSION['REAL_REFERER'];
        unset($_SESSION['REAL_REFERER']);
    }
    else {
        $referer = $_SERVER['HTTP_REFERER'];
    }
    
  2. Send referer as parameter:

    // in your first script
    header('Location: http://iquality.itayb.net/index-he.html?referer=' . $_SERVER['HTTP_REFERER']);
    
    // in your refered script extract from the parameter
    $referer = '';
    if (isset($_REQUEST['referer'])) {
        $referer = $_REQUEST['referer'];
    }
    else {
        $referer = $_SERVER['HTTP_REFERER'];
    }
    

If you want to cheat any other server then use something like this:

$host = 'www.yourtargeturl.com';
$service_uri = '/detect_referal.php';
$vars ='additional_option1=yes&additional_option2=un';

$header = "Host: $host\r\n";
$header .= "User-Agent: PHP Script\r\n";
$header .= "Content-Type: application/x-www-form-urlencoded\r\n";
$header .= "Referer: {$_SERVER['HTTP_REFERER']} \r\n";
$header .= "Content-Length: ".strlen($vars)."\r\n";
$header .= "Connection: close\r\n\r\n";

$fp = fsockopen("".$host,80, $errno, $errstr);
if (!$fp) {
  echo "$errstr ($errno)<br/>\n";
  echo $fp;
} else {
    fputs($fp, "POST $service_uri  HTTP/1.1\r\n");
    fputs($fp, $header.$vars);
    fwrite($fp, $out);

    while (!feof($fp)) {
        echo fgets($fp, 128);
    }
    fclose($fp);
}
Share:
24,789
iTayb
Author by

iTayb

Just another guy surfing the web (:

Updated on July 12, 2022

Comments

  • iTayb
    iTayb almost 2 years

    I have the following PHP redirect script:

    if ($country=="IL") { header('Location: http://iquality.itayb.net/index-he.html'); }
    else { header('Location: http://iquality.itayb.net/index-en.html'); }
    

    This redirects the user to different pages, according to $country's value. The referrer becomes the redirection page itself.

    How can I preserve the original referrer field?

  • Falk
    Falk almost 10 years
    isn't it with jurst onr R 'HTTP_REFERER' instead of two 'HTTP_REFERRER'?
  • rockyraw
    rockyraw over 9 years
    what is detect_referal.php?