Http referer php code

Что такое реферер или как использовать HTTP-заголовок referer

Что такое реферер? Заголовок HTTP referer передается с браузера на сервер, чтобы сообщить, на какой странице читатель находился перед тем, как перешел на вашу. Данная информация может быть использована, чтобы предоставить специальные предложения для целевых посетителей, перенаправить клиентов или сгруппировать посетителей сайта по определенным критериям.

Можно использовать такие языки, как JavaScript , PHP или ASP , чтобы считать информацию, содержащуюся в заголовке referer . А также добавить строки кода в файл .htaccess .

Сбор из referer с помощью PHP, JavaScript и ASP

PHP хранит информацию из referer в системной переменной HTTP_REFERER . Чтобы отобразить ее на PHP-странице , нужен следующий код:

if(isset($_SERVER[‘HTTP_REFERER’]))

Он проверяет, содержит ли переменная значение, а затем выводит его на экран. Вместо echo $_SERVER[‘HTTP_REFERER’]; можно задать строки скрипта таким образом, чтобы проверить различные referer .

Читайте также:  Java unit test factory

JavaScript использует для чтения server http referer DOM . Так же, как в случае с PHP , нужно проверить, содержит ли заголовок значение. Если вы хотите управлять переменно, то сначала нужно установить данную переменную. Вот как отобразить referer на странице с помощью JavaScript .

Обратите внимание, что DOM использует альтернативное написание referer :

После этого можно использовать заголовок в скрипте с переменной myReferer .

ASP , как и PHP , устанавливает referer в качестве системной переменной. После чего нужно получить данную информацию следующим образом:

if (Request.ServerVariables(«HTTP_REFERER»))

Также можно настроить скрипт с использование переменной myReferer .

После того как вы получили referer, что с ним делать?

После того, как вы получили информацию из HTTP referer , ее можно использовать в скриптах сайта. Например, чтобы вывести данные о том, откуда пришли посетители. Но гораздо интереснее использовать заголовок для отображения различной информации в зависимости от того, откуда пришли пользователи.

Общее приветствие

Можно вывести URL-адрес из referer в верхней части страницы в общем приветствии:

  

Приветствие посетителей из поисковой системы

Когда кто-то перешел на ваш сайт из поисковой системы, можно предоставить таким пользователям немного дополнительной информации, чтобы побудить их дольше оставаться на ресурсе. Например, вывести для них ссылку на новостную рассылку сайта:

  

Передача информации в формы

Если у вас на сайте есть ссылка, кликнув по которой посетители могут сообщить о проблемах с ресурсом. Люди часто сообщают о проблемах с веб-страницей без указания URL-адреса , на котором она возникла. Но можно использовать информацию из server http referer , чтобы предположить, о какой проблеме на какой странице идет речь.

Этот скрипт добавляет referer в скрытое поле формы:

  

Создание специального предложения для определенных посетителей

Возможно, вы захотите предоставить людям, которые приходят с конкретной страницы, специальное предложение на ваши товары или услуги. C этой целью можно было бы открыть новое окно, чтобы предложить страницу. Но помните, что людям не всегда нравятся всплывающие окна, так что используйте их осторожно:

 

Направление посетителей на другую страницу

Также можно направить людей с определенным HTTP referer на другую страницу. Будьте осторожны, так как Google и другие поисковые системы могут расценить это, как введение в заблуждение, и наказать ваш сайт:

 

Блокирование пользователей по referer с помощью .htaccess

Если вы страдаете от referer-спама с одного домена, можно просто заблокировать его на вашем сайте. Если вы используете Apache с установленным mod_rewrite , тогда можно блокировать спам с помощью нескольких строк кода ( rewritecond http referrer , запрет входа без referrer ).

Добавьте следующие строки в файл .htaccess :

RewriteEngine on # Options +FollowSymlinks RewriteCond % spammer.com [NC] RewriteRule .* - [F]

Измените spammer.com на домен, который нужно заблокировать. Не забудьте добавить перед периодами в домене.

Не полагайтесь на referer

Помните, что возможна подмена HTTP referer , поэтому не стоит использовать его для важных страниц. Лучше применять его в качестве дополнения. Но если страница должна быть доступна только конкретным пользователям, то придется установить для нее пароль через файл htaccess .

Источник

Using the HTTP_REFERER variable with PHP

When a web browser moves from one website to another and between pages of a website, it can optionally pass the URL it came from. This is called the HTTP_REFERER, and this post looks at how to use this variable with PHP.

Overview of http referers

Most web browsers pass the HTTP_REFERER variable by default, but in many this behaviour can be changed to not show it or to pass something else instead. There is also 3rd party anti-spyware etc software that can be installed on a user’s computer which also prevents the referrer information from being passed to the web server. Because it can also be changed to something else, the HTTP_REFERER cannot be trusted, but it is still useful for working out where people have come from.

Appearance in log files

The following examples are from an Apache web server’s log files.

The first example shows what a log entry looks like from someone coming from this website’s homepage to this particular post. I have made the HTTP REFERER part of the log line bold (you’ll need to scroll to the right to see it).

192.168.1.10 - - [16/Apr/2008:16:12:36 +1200] "GET /php-http-referer-variable/ HTTP/1.1" 200 2014 "https://www.electrictoolbox.com/" Mozilla/5.0 (compatible; Konqueror/3.5; Linux) KHTML/3.5.8 (like Gecko)"

The second example shows the same thing, but because it is represented by a – only it tells us the user has either gone directly to that page by typing the address in or using a bookmark etc, or is masking the HTTP REFERER with a browser option or a 3rd party tool.

192.168.1.10 - - [16/Apr/2008:16:12:36 +1200] "GET /php-http-referer-variable/ HTTP/1.1" 200 2014 "-" Mozilla/5.0 (compatible; Konqueror/3.5; Linux) KHTML/3.5.8 (like Gecko)"

Using HTTP_REFERER in PHP

The HTTP REFERER in PHP is stored in the $_SERVER super global, and can be referenced from anywhere in your PHP code like in the following example, which would simply write it out to the browser:

If the HTTP_REFERER has been set then it will be displayed. If it is not then you won’t see anything. If it’s not set and you have error reporting set to show notices, you’ll see an error like this instead:

Notice: Undefined index: HTTP_REFERER in /path/to/filename.php on line 3

To prevent this error when notices are on (I always develop with notices on), you can do this:

if(isset($_SERVER[‘HTTP_REFERER’]))

echo isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : '';

The use of the ? operator will return the first value after the ? if the condition is true and the second value if the condition is false. It can be useful to use when you are wanting to assign the value of the HTTP_REFERER to a variable. e.g.:

$referer = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : '';

Conclusion

It can be useful to use the HTTP_REFERER variable for logging etc purposes using the $_SERVER[‘HTTP_REFERER’] superglobal variable. However it is important to know it’s not always set so if you program with notices on then you’ll need to allow for this in your code. The above examples show one way of doing this.

Follow up posts

Have a read of my post titled «PHP: get keywords from search engine referer url» to find out how to use the HTTP_REFERER value to see what query string visitors have entered into a search engine.

Источник

Example PHP code to retrieve HTTP referer in PHP

The information stored in an array includes headers, paths, and script locations, but not all web servers will offer these details. Some servers may not have all the information listed, or they may provide additional information not mentioned here.

Using PHP’s $_SERVER[‘HTTP_REFERER’] Without Recognizing Parameters

To verify if the desired URL matches with HTTP_REFERER , the simplest approach is to check whether HTTP_REFERER commences with the same URL.

if (strpos($_SERVER[‘HTTP_REFERER’], ‘http://www.example.com’) === 0))

The solution provided by @EmilyShepherd ought to be effective.

To only verify the domain, which is beneficial due to certain websites permitting exclusion of (www.) and being accessible through both (https://) and (http://).

if (strpos($_SERVER['HTTP_REFERER'], 'example.com')) 

It should be noted that referring sources can be susceptible to spoofing.

You can also try using this

$url = $_SERVER['HTTP_REFERER']; $data = parse_url($url); $referer= $data['host']; if($referer== 'www.example.com') < // Some codes here >/* var_dump($data); Array ( [scheme] => http [host] => www.example.com [path] => /path/to/ [query] => here=there ) */ 

You can obtain the paths and query string of the referer using this feature.

It is advisable to extract the host name for matching if your scheme could be either http or https . This would be more efficient than having to check both schemes. The extracted host name can be found in www.example.com .

Php — $_SERVER[‘HTTP_REFERER’], Note that the HTTP_REFERER bit is placed within <> in the string. That’s to force it to extrapolate the value (I don’t like string concatenation). Also note that, as has been said above, there’s no guarantee that the REFERER will have the right value, or any value at all.

Getting referrer using php

You have the option to store the information either in a cookie or a session, allowing you to access it on subsequent pages.

if (!isset($_SESSION)) < session_start(); >if (!isset($_SESSION['referrer'])) < $_SESSION['referrer'] = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : 'n/a'; >// another page $referer = isset($_SESSION['referrer']) ? $_SESSION['referrer'] : null; 

The referer may be included, however, it is limited to a single level, allowing you to trace the previous step of the visitor but not two steps back.

By utilizing $_SERVER[‘HTTP_REFERER’] , the referrer will be obtained in case it exists.

PHP: How to get referrer URL?, $_SERVER [‘HTTP_REFERER’] will give you the referrer page’s URL if there exists any. If users use a bookmark or directly visit your site by manually typing in the URL, http_referer will be empty. Also if the users are posting to your page programatically (CURL) then they’re not obliged to set the http_referer as …

Using $_SERVER[‘HTTP_REFERER’] With GET Variables

To ensure simplicity and reliability, it’s advisable to include a GET parameter in your homepage links and subsequently verify its presence instead of other complex alternatives.

An alternative approach could be to utilize the stristr() function with $_SERVER[‘HTTP_REFERER’] and search for the term ‘index’.

There is no doubt that Matt’s response is more trustworthy.

$_SERVER deprecated, how to $_GET http_referer?

While $_SERVER is still in use, $HTTP_SERVER_VARS has been deprecated.

As per the documentation on http://php.net/manual/en/reserved.variables.server.php, it is worth noting that $HTTP_SERVER_VARS is deprecated, whereas $_SERVER is not. Thus, you can use $_SERVER[‘HTTP_REFERER’] without any concerns.

$HTTP_SERVER_VARS is deprecated, $_SERVER is not!

The array $_SERVER holds various details, such as headers, paths, and script locations, which are generated by the web server. It is not ensured that all web servers will provide every detail mentioned here, and some servers may include other details not listed. However, most of these variables are covered under the CGI/1.1 specification, so you can anticipate them.

The information in $HTTP_SERVER_VARS is identical, but it is not a superglobal. It’s important to note that $HTTP_SERVER_VARS and $_SERVER are distinct variables and are treated as such by PHP.

Referrer URL in PHP, I am using this code to store the referrer URL in my form for tracking conversions, the problem I have is that the URL it stores is the URL which the form is on and not the URL where the visitor came from. I am trying to get the URL of the website that the user came from, i.e if the user came from google I need the URL …

Источник

Оцените статью