This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable,
visit the help center.
Closed 6 years ago.
I'm using this code wanting to display the url used to access this page:
<?php
$referer = $_SERVER['HTTP_REFERER'];
echo ($referer);
?>
So when I've got this code in file index.php, put it onder www.mysite.com/index.php and I go to www.mysite.com, it should display 'www.mysite.com', shouldn't it?
When I use it though is displays nothing. Not locally on Mamp and also not online. What am I doing wrong?
$_SERVER['HTTP_REFERER']
tells you where you came from, not the page you're loading. If you want to show www.mysite.com, you're probably looking for $_SERVER['HTTP_HOST']
.
If you want the full URL used to access the page, you're probably after $_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']
.
To make it easier to understand, these would be the variable values^ if you clicked a link from http://www.mysite.com/index.php to http://www.mysite.com/anotherpage.php:
$_SERVER['HTTP_REFERER'] = "http://www.mysite.com/index.php"
$_SERVER['HTTP_HOST'] = "www.mysite.com"
$_SERVER['REQUEST_URI'] = "/anotherpage.php"
$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'] = "www.mysite.com/anotherpage.php"
Hope this helps, the full documentation on PHP $_SERVER
reserved variables may help you more.
^ Not all browsers set the HTTP_REFERER
variable. It is optional in the RFC and as such you shouldn't rely on it being there to do any functionality.
The referer header is an optional header the browser sends when requesting a page, informing the server of the previous page it came from. So for the first page you type into the browser, there will be no referer. After you click on a link from one page to another, there may be a referer set.