Why is the http referer not showing? [closed]

2020-05-06 08:12发布

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?

标签: php http
2条回答
Root(大扎)
2楼-- · 2020-05-06 08:32

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.

查看更多
Animai°情兽
3楼-- · 2020-05-06 08:40

$_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.

查看更多
登录 后发表回答