How to use proxy with curl in php

Proxy with Curl

Curl is a very useful library for transferring data over various protocols like http, ftp, https etc. In other words curl can be used to programatically download a web page, or upload file to ftp etc. It also supports using a proxy. This means that curl requests can go through a proxy server just like a web browser does when configured to use a proxy.

Using a proxy with curl is very simple and straight forward. Lets take a look at a simple curl request in php that fetches a url.

Fetch url directly

The following program fetches the contents of a URL directly, without using any proxy.

//gets the data from a URL
function get_url($url) 
{
    $ch = curl_init();
     
    if($ch === false)
    {
        die('Failed to create curl object');
    }
     
    $timeout = 5;
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
    $data = curl_exec($ch);
    curl_close($ch);
    return $data;
}
 
echo get_url("http://www.apple.com/");

Now that same request can be made to go through a proxy. Now proxies are of 2 kinds, SOCKS and HTTP. Curl can use either type. Curl needs to be told the ip address and port number of the proxy server. To run the next piece of code you would need a working proxy server.

I would recommend using TOR, which is the best proxy/anonymity service out there and it is always in a working condition. You do not have to search for working proxies here and there instead. Just install tor and start it.
If you got some other working proxy that too will work just fine.

Use socks proxy with curl

This code example demonstrates how to use a socks proxy with curl in php

$url = "http://www.ipmango.com/api/myip";
$ch = curl_init();
	
if($ch === false)
{
	die('Failed to create curl object');
}
	
$timeout = 5;
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);

//proxy details
curl_setopt($ch, CURLOPT_PROXY, 'localhost:9050');
curl_setopt($ch, CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5);

$data = curl_exec($ch);
curl_close($ch);

echo $data;

The above code fetches the remote url http://www.ipmango.com/api/myip which tells the public ip of the requesting machine. If a proper proxy is running on localhost at 9050 (tor in this case) then the returned ip should be a different ip than the real ip of the user. To see the difference, comment out the proxy details and compare the ip addresses returned.







Last Updated On : 14th July 2013

Subscribe to get updates delivered to your inbox

2 Comments + Add Comment

  • not working , I tried 4 parameters about proxy but all failed

  • not working

Leave a comment