Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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 );
	}
	
	public function changeProxyIdentity()
	{
		$ip      = '127.0.0.1';
		$port    = '9050';

		$fp = fsockopen(
		    $ip, $port,
		    $error_number,
		    $err_string, 10
		);

		if (!$fp) {
		    echo "Error while changing Tor proxy identity: {$error_number} : {$err_string}";
		    return false;
		} else {
		    fwrite($fp, "AUTHENTICATE\n");
		    $received = fread($fp, 512);
		    fwrite($fp, "signal NEWNY\n");
		    $received = fread($fp, 512);
		}

		fclose($fp);

		return $received;
	}
    
	function __destruct() 
	{
		curl_close( $this->ch );
	}

}

Use the Proxy class for a GET request.

$proxy = new Proxy();
$proxy->changeProxyIdentity();
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 );
@nguyenkhanhdev

This comment has been minimized.

Copy link

nguyenkhanhdev commented Jul 16, 2018

How to config to change Proxy to get new IP for each time we send a request?

@atefBB

This comment has been minimized.

Copy link
Owner Author

atefBB commented Aug 7, 2018

Hey @nguyenkhanhdev !
Sorry for the delay.
You can simply do like:

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

This comment has been minimized.

Copy link

Dibbyo456 commented Aug 13, 2018

@atefBB Does not change IP every time..

@atefBB

This comment has been minimized.

Copy link
Owner Author

atefBB commented Apr 28, 2019

@Dibbyo456 Changing IP may take a while in Tor.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.