Checking PHP referrer

So, I need to check the referrer on the page using php, and if it is * .example.com or * .anothersite.com, execute the code, but if not, redirect to another place.

How do I check if HTTP_REFERER matches these values ​​with a wildcard?

Thanks!

EDIT: The URL will contain more than one domain, so the regular expression must match the FIRST found.

+4
source share
5 answers
$ref = $_SERVER['HTTP_REFERER']; if (strpos($ref, 'example.com') !== FALSE) { redirect to wherever example.com people should go } if (strpos($ref, 'example.org') !== FALSE) { redirect to wherever example.org people should go } 

Of course, this only works if the referent is "good." For example, from Google, you could have "example.org" in search terms somewhere, in which case strpos will see it and redirect it, even if you come from Google.

+4
source

Should do it:

 $allowed_host = 'example.com'; $host = parse_url($_SERVER['HTTP_REFERER'], PHP_URL_HOST); if(substr($host, 0 - strlen($allowed_host)) == $allowed_host) { // some code } else { // redirection } 
+13
source

Other response checks are good, but not strictly related to your site. So, for example, the referent with the value http://attacker.com/www.example.com/ will pass almost all the checks. And it’s very easy to make such a site and just send a request for cross-domain communication.

There is a reliable and safe way to check if the referent is valid . Of course, the referent can be faked, but the victim of the attacker will send the correct referent.

The trick is in ^ special character. Here is a magical regex:

 ^https?://(([a-z0-9-]+)\.)*example\.com/ 

^ - ensures that we are at the beginning
https? - protocol - http or https
(([a-z0-9-]+)\.)* - corresponds to subdomains, as well as to higher levels, if any example\.com - corresponds to the main domain
/ - ensures that the path starts, so the domain name cannot continue

+2
source

Try the following:

 if (preg_match('/\.example\.(com|org)/', $_SERVER['HTTP_REFERER'])) { // execute your code } else { header("Location: http://example.com/redirectpage.htm"); exit(); } 
+1
source

preg_match('/(.+?)\.example\.(com|org)/',$_SERVER['HTTP_REFERER'])

This will correspond to an address that has a subdomain, and it will also not continue to search for anything outside of subdomain.example.com or .org . those. subdomain.example.com/some-other-stuff . Do you need to match any of them as well?

Correction - this will correspond to www.example.com , but will not correspond to example.com .

+1
source

Source: https://habr.com/ru/post/1340213/


All Articles