Luke14
Luke14

Reputation: 106

Redirect visitor based on referral URL

I want to redirect visitors to one page on my website if they have come from a certain URL and another if they don't.

<?
$referer = $_SERVER['HTTP_REFERER'];
if ( $referer != "http://URL1" ) {
  header('Location: page1');
  exit;
 } else {
  header('Location: page2');
 }
?>

Whatever referrer I come to the page on it goes to page 1 and never to page 2. I have used this code in a index.php file so its the first page the visitor is directed too.

Upvotes: 2

Views: 3759

Answers (2)

Stoic
Stoic

Reputation: 10754

UPDATE: alright, so from the discussions, it seems that the reason why your code won't work is that you are checking the referer string using the "now-www" url, while the actual referer string has "www" in the url. Please, make sure to use the exact referer string. Otherwise, if you are redirecting based on the hostname of the referer you can use the updated answer below.

<?php
$referer = str_replace("www.", "", parse_url($_SERVER['HTTP_REFERER'], PHP_URL_HOST));
switch($referer) {
  case "johnchow.com":
    header("Location: page1");
    break;
  case "domain2.com":
    header("Location: page2");
    break;
  default:
    header("Location: page3");
}
exit;

Upvotes: 3

mseifert
mseifert

Reputation: 5670

For starters change this to

if ( $referer != "http://URL1" || $referer != "http://URL2" )

Secondly, page1 and page2 are likely giving the error because they are invalid. Include the path and extension. For example:

header('Location: http://www.yourlocation/page1.php')

Looks like the error has been clarified...

Upvotes: 0

Related Questions