Question

Can you please suggest simple PHP script that I can insert to web-page, that will track and record every HTTP_REFERER of users that came to web-page? Thank you so much for help in advance

Was it helpful?

Solution

Using $_SERVER['HTTP_REFERER'] is not reliable.

However, if you still want to go that route, you can use the following.

What this does is use a ternary operator to check if the referer is set.

If a referer is found, then it will record to it to file, and appending/adding to it using the a switch. Otherwise, if one is not found or isn't recordable, it will simply echo and not write anything to file.

If you don't want to keep adding to the file, use the w switch.

Caution - Using the w switch will overwrite any previously-written content.

<?php
$refer = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : null;

if(!empty($refer)){

    $fp = fopen('file.txt', 'a');
    fwrite($fp, "$refer" . "\n"); // Using \n makes a new line. \r\n Windows/MAC
    fclose($fp);
    echo "Referer found and written to file.";
}

else{
echo "No referer, nothing written to file.";
}

// Or use this to write "No referer" in the file as a replacement
/*
else{
    $fp = fopen('file.txt', 'a');
    fwrite($fp, "No referer" . "\n");
    fclose($fp);
    echo "No referer.";
}
*/

OTHER TIPS

this is a very simple script that will let you archive it:

$fp = fopen('myfile.txt', 'w');
fwrite($fp, $_SERVER['HTTP_REFERER']);
fclose($fp);

It might be a better idea to log this in apache (if thats the platform).

About logfiles: http://httpd.apache.org/docs/1.3/logs.html

Then use some designated software to analyze the logs.

The reason for this is that to build your own tracking-script is a lot more work than it might seem, even at the simplest level. If its to be usable.

Another idea is to install some logging software from 3rd party. I think statcounter uses logfiles and can give you what you want for instance.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top