- wp_get_referer() │ WP 2.0.4
- Возвращает
- Использование
- Примеры
- #1 Выведем ссылку «Вернуться назад»
- #2 Что выводит функция
- Список изменений
- Код wp_get_referer() wp get referer WP 6.2.2
- Cвязанные функции
- Без рубрики
- URL Functions
- Using the HTTP_REFERER variable with PHP
- Overview of http referers
- Appearance in log files
- Using HTTP_REFERER in PHP
- Conclusion
- Follow up posts
- Check Out These Related posts:
- Determine Referer in PHP
- Determine Referer Using $_SESSION[] in PHP
wp_get_referer() │ WP 2.0.4
Получает реферер ссылку (referer URL), только если это внутренний URL — URL текущего сайта. Вернет false, если реферер равен текущей странице. Эта функция — это объединение двух функций: wp_get_raw_referer() и wp_validate_redirect().
Возвращает
Использование
Примеры
#1 Выведем ссылку «Вернуться назад»
Допустим мы в админке сайта перешли по ссылке на страницу нашего плагина и нам нужно на этой странице среди прочего вывести ссылку «Вернуться назад». Решение такой задачи может выглядеть так:
Тут надо заметить, что такая ссылка будет показана, только если на страницу зашли с другой страницы. Но если на этой же странице, например, обновить данные формы, то реферер будет равен текущему URL и ссылка «Вернуться назад» не будет выведена. В этом случае, чтобы ссылка «Вернуться назад» работала как нужно, её надо куда-то сохранить при первом посещении страницы (например в транзитные опции) и при совпадении URL брать от туда.
#2 Что выводит функция
echo wp_get_referer(); // /some-page?foo=bar
Список изменений
Код wp_get_referer() wp get referer WP 6.2.2
function wp_get_referer() < if ( ! function_exists( 'wp_validate_redirect' ) ) < return false; >$ref = wp_get_raw_referer(); if ( $ref && wp_unslash( $_SERVER['REQUEST_URI'] ) !== $ref && home_url() . wp_unslash( $_SERVER['REQUEST_URI'] ) !== $ref ) < return wp_validate_redirect( $ref, false ); >return false; >
Cвязанные функции
Без рубрики
- _doing_it_wrong()
- cache_javascript_headers()
- do_robots()
- download_url()
- get_privacy_policy_url()
- maybe_convert_table_to_utf8mb4()
- nocache_headers()
- show_admin_bar()
- wp_check_browser_version()
- wp_die()
- wp_editor()
- wp_get_raw_referer()
- wp_install_defaults()
- wp_magic_quotes()
- wp_mail()
- wp_oembed_get()
- wp_redirect()
- wp_safe_redirect()
- wp_star_rating()
- wp_timezone_choice()
- wp_validate_redirect()
URL Functions
Note that $_SERVER[«HTTP_REFERER»] may not include GET data that was included in the referring address, depending on the browser. So if you rely on GET variables to generate a page, it’s not a good idea to use HTTP_REFERER to smoothly «bounce» someone back to the page he/she came from.
just a side note to the above you will need to add the ?
Note also that the URL shown in $HTTP_REFERER is not always the URL of the web page where the user clicked to invoke the PHP script.
This may instead be a document of your own web site, which contains an HTML element whose one attribute references the script. Note also that the current page fragment (#anchor) may be transmitted or not with the URL, depending on the browser.
Examples:
In such case, browsers should transmit the URL of the container document, but some still persist in using the previous document in the browser history, and this could cause a different $HTTP_REFERER value be sent when the user comes back to the document referencing your script. If you wanna be sure that the actual current document or previous document in the history is sent, use client-side JavaScript to send it to your script:
And then check the value of $js in your page script to generate appropriate content when the remote user agent does not support client-side scripts (such as most index/scan robots, some old or special simplified browsers, or browsers with JavaScript disabled by their users).
Following method do not show the URL in user browser (as the author claimed) if the code resides in the source page of FRAME or IFRAME (say SRC=»sourcepage.php») . In that case the URL of the SOURCE page is displayed.
$url = sprintf(«%s%s%s»,»http://»,$HTTP_HOST,$REQUEST_URI);
echo «$url»;
To check if a URL is valid, try to fopen() it. If fopen() results an error (returns false), then PHP cannot open the URL you asked. This is usually because it is not valid.
When using a multiple select on a form, I ran into a little issue of only receiving the last value form the select box.
I had a select box named organization_id with two values (92 and 93).
To get the values of both, I had to use the following:
$temp_array = split(«&», $_SERVER[‘QUERY_STRING’]);
foreach($temp_array as $key=>$value) if(substr($value, 0, 15) == «organization_id») $_GET[‘organizations’][] = substr($value, 15, strlen($value));
>
>
this results in a $_GET array like this :
(
[page] => idea_submission
[organization_id] => 93
[organizations] => Array
(
[0] => =92
[1] => =93
)
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.
Check Out These Related posts:
Determine Referer in PHP
The $_SERVER[‘HTTP_REFERER’] gives us referer URL to determine user requests on the server. But, it is not a best practice since the referer can be compromised over HTTP .
Determine Referer Using $_SESSION[] in PHP
Since the HTTP_REFERER can be spoofed/faked, PHP allows us to use sessions/cookies to determine whether an incoming user request is from your domain (server) or not.
- userrequest.php : Stored user session id in URL , set it true and applied mt_rand() to aid additional security.
- determineuser.php : Determined referer (domain/server) location using session and $_SERVER[‘HTTP_REFERER’] .