views:

166

answers:

2

I am trying to redirect visitors to a site based on their referring url.

Here is the script:

php
$domain='blankds.com';
$referrer=$_SERVER['HTTP_REFERER'];
echo $referrer;
if (preg_match("/$domain/",$referrer)) {
 header('Location: http://www.blackisgreen.org/page_1.php');
 } else {
 header('Location: http://www.blackisgreen.org/page_2.php');
};

Errors: I get a "Warning: cannot modify header" error because I am echoing $referrer before sending headers.

If I remove the echo the script does not work.

Any suggestions?

A: 

PHP is sending headers to the user requesting the page when you echo $referrer. The header function you are then calling attempts to modify these headers and affix a location redirect but cannot as the headers have already been sent along with the start of your page content.

To get around this problem, take a look at PHP's Output Control functions, especially ob_start(); which inserted at the top of your script should allow you to continue echoing the redirect location and allowing you to redirect at the same time.

JoeR
A: 

Just as a note: Any output will auto-generate headers. If you want to redirect with headers you just need to comment out echo $referrer; If you need to see what referrer is going to which site for debugging purposes, just put it in the URL, the receiving page should ignore it.

TheLQ