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:
- To get around regional filters and country blocks.
- Using a proxy IP allows you to mask your own IP address.
- 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 = '220.127.116.11';
//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.
throw new Exception(curl_error($ch));
//Print the 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 18.104.22.168 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 22.214.171.124 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.