PHP: Capture Referring URL And Truncate It To Domain Name

Richard CummingsQuick Solutions, Technologies/Solutions, Web ConsultingLeave a Comment

This is a quick technical post on how to use PHP to capture a referring URL and truncate it to a domain name. In other words, we want to determine the exact domain name from which our visitors arrived.

The reasons for doing this are numerous. Many use this referring information for statistical analysis while others use it to perform a particular action. If visitor came from, then do this.

By the way, it looks like you came directly to this page. How do I know? Well, that is what this post is about so read on!“;


else {

$myhost = $url[‘scheme’].”://”.$url[‘host’];

echo “By the way, it looks to me that you have come here from $myhost! That could be valuable information for a website owner, no? How do I know from whence you came? Well, that is what this post is about so read on! “;


Whatever your reasons, let’s take a look at how to accomplish this. It’s just a few simple lines of code that I have included, with comments, below:

PHP Code For Determining Referring URLs & Extracting Domain Names

$ref=@$HTTP_REFERER;  // this gets the entire URL from where your visitors arrived
$url = parse_url($ref);  // this parse_url PHP function returns the various elements of that URL
$checkresult=$url['host'];  // This is not required.  I use it to determine if there is a referring URL (some users visit your page directly).
// This is the if empty statement.  If empty, then do this...
	if (empty($checkresult))
{echo "There is no referring URL.";
else {
$myhost = $url['scheme']."://".$url['host'];  //  this truncates the referring URL down to just the domain name
echo "Your referring URL is $myhost!";


Conclusion: Capturing Referring URLs

I tried to comment the code above so that you would see what each line is doing. To test this out immediately, simply copy the code into your favorite text editor, give it a PHP extension, upload it to your server, and play around with it.

Obviously, this article assumes some base PHP knowledge but I hope that is has been helpful to some out there who are trying to extract referring URLs. If you have any questions, ask them below and I will try to answer them if time permits.


Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.