PHP: Using cURL with a proxy.

This is a guide on how to use a proxy with PHP’s cURL functions. In this tutorial, we will send our HTTP request via a specific proxy IP and port.

Why use a proxy?

There are various reasons why you might want to use a proxy with cURL:

  1. To get around regional filters and country blocks.
  2. Using a proxy IP allows you to mask your own IP address.
  3. To debug network connection issues.

Using a proxy with PHP’s cURL functions.

Take a look at the following PHP code, which you can use to authenticate with a proxy via cURL and send a HTTP GET request.

//The URL you want to send a cURL proxy request to.
$url = 'http://php.net';

//The IP address of the proxy you want to send
//your request through.
$proxyIP = '1.2.3.4';

//The port that the proxy is listening on.
$proxyPort = '1129';

//The username for authenticating with the proxy.
$proxyUsername = 'myusername';

//The password for authenticating with the proxy.
$proxyPassword = 'mypassword';


$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL , 1);

//Set the proxy IP.
curl_setopt($ch, CURLOPT_PROXY, $proxyIP);

//Set the port.
curl_setopt($ch, CURLOPT_PROXYPORT, $proxyPort);

//Specify the username and password.
curl_setopt($ch, CURLOPT_PROXYUSERPWD, "$proxyUsername:$proxyPassword");

//Execute the request.
$output = curl_exec($ch);

//Check for errors.
if(curl_errno($ch)){
    throw new Exception(curl_error($ch));
}

//Print the output.
echo $output;

In the code snippet above, we connected to a proxy that requires authentication before sending a simple GET request.

If the proxy in question does not require authentication, then you can omit the CURLOPT_PROXYUSERPWD line from your code.

“Failed to connect to 1.2.3.4 port 1129: Timed out”

This means that cURL could not connect to the proxy on that IP and port. Make sure that both the IP and port are correct and that the proxy is operating correctly.

“Failed to connect to 1.2.3.4 port 1129: Connection refused”

This error usually occurs when you have specified an incorrect port number. i.e. The IP address of the proxy was correct, but it is not listening for requests on that port. There is also the possibility that the server is up, but the software that runs the proxy is not running.

“Received HTTP code 407 from proxy after CONNECT”

The username and password combination that you are using with CURLOPT_PROXYUSERPWD is incorrect. Make sure that you are separating the username and password by a colon : character.