Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to redirect preserving original referrer field?

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?

like image 747
iTayb Avatar asked Feb 02 '13 10:02

iTayb


1 Answers

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);
}
like image 168
Viacheslav Dobromyslov Avatar answered Sep 30 '22 19:09

Viacheslav Dobromyslov