Skip to content

Instantly share code, notes, and snippets.

@megaxorg
Last active December 2, 2022 20:23
Show Gist options
  • Save megaxorg/acfdce73976f219a6695 to your computer and use it in GitHub Desktop.
Save megaxorg/acfdce73976f219a6695 to your computer and use it in GitHub Desktop.
PHP: CURL Requests with Tor

#CURL Connections with Tor

Install Apache, PHP, CURL & Tor with apt-get

sudo apt-get install -y apache2 php5 php5-curl tor

Tor creates a proxy on your mashine with port 9050 for SOCKS5 connections.

class Proxy {

	private $ch, $proxy;

	function __construct() {

		$torSocks5Proxy = "socks5://127.0.0.1:9050";

		$this->ch = curl_init();

		curl_setopt( $this->ch, CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5 );
		curl_setopt( $this->ch, CURLOPT_PROXY, $torSocks5Proxy );
		curl_setopt( $this->ch, CURLOPT_SSL_VERIFYPEER, false );
		curl_setopt( $this->ch, CURLOPT_FOLLOWLOCATION, true );
		curl_setopt( $this->ch, CURLOPT_RETURNTRANSFER, false );
		curl_setopt( $this->ch, CURLOPT_HEADER, false );

	}

	public function curl( $url, $postParameter = null ) {

		if( sizeof( $postParameter ) > 0 )
			curl_setopt( $this->ch, CURLOPT_POSTFIELDS, $postParameter );

		curl_setopt( $this->ch, CURLOPT_URL, $url );
		return curl_exec( $this->ch );

	}

	function __destruct() {

		curl_close( $this->ch );

	}

}

Use the Proxy class for a GET request.

$proxy = new Proxy();
echo $proxy->curl( "http://check.torproject.org" );

Use the Proxy class for a POST request

$proxy = new Proxy();
$parameter = array(
	'parameter1' => 'value1',
	'parameter2' => 'value2'
	);
echo $proxy->curl( "http://check.torproject.org", $parameter );
@atefBB
Copy link

atefBB commented Mar 22, 2018

Thanks, that's helps !
@sxss I added the ability to change the proxy identity, see https://gist.github.com/atefBB/7a43fe65848c9208b59409c145bfa59f.

@tridento
Copy link

you cant resolve .onion sites with $torSocks5Proxy = "socks5://127.0.0.1:9050";
replace it with $torSocks5Proxy = "127.0.0.1:9050";
define another CURLOPT_PROXYTYPE: curl_setopt( $this->ch, CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5_HOSTNAME );
and it works like a charm.

@akadi81
Copy link

akadi81 commented Oct 2, 2018

It's not working with php 7.2

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