Skip to content

Instantly share code, notes, and snippets.

@jeroenvisser101
Last active September 29, 2019 10:59
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save jeroenvisser101/cb7e01f58b229b946b99 to your computer and use it in GitHub Desktop.
Save jeroenvisser101/cb7e01f58b229b946b99 to your computer and use it in GitHub Desktop.
Detecting people that use Tor
<?php
/**
* Class TorDetector
*
* Helps to detect if visitors are using a Tor browser to surf the website.
*
* Thanks to https://trac.torproject.org/projects/tor/wiki/doc/TorDNSExitList
*/
class TorDetector
{
/**
* Checks if a user is currently reaching the server from a Tor exit node.
*
* @param string $remoteIp The IP of the visitor you'd like to check.
* @param int $port The port on which the server is running.
* @param string $serverIp Your server IP.
*
* @return bool
*/
public function check($remoteIp, $port, $serverIp)
{
$detectHost = sprintf(
'%s.%s.%s.ip-port.exitlist.torproject.org',
$remoteIp,
$port,
$this->reverseIPOctets($serverIp)
);
// According to the guide, if this returns 127.0.0.2, it's a Tor exit node
return gethostbyname($detectHost) === '127.0.0.2';
}
/**
* This function simply reverses the IP's octets.
*
* @param string $ip The IP to be reversed.
*
* @return string
*/
protected function reverseIPOctets($ip)
{
return implode('.', array_reverse(explode('.', $ip)));
}
}
@dsoares
Copy link

dsoares commented Jun 16, 2016

The correct syntax is:
return implode('.', array_reverse(explode('.', $ip)));

@jeroenvisser101
Copy link
Author

@dsoares correct and updated!

@dfsmirnov
Copy link

According to https://trac.torproject.org/projects/tor/wiki/doc/TorDNSExitList remoteIp need to be inverced too

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment