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.";
}
*/