Using Proxy Servers with cURL in PHP

Tutorial on how to use proxy servers with cURL and PHP

Edited: 2016-10-05 03:49

Setting a proxy server to be used with cURL and PHP is relatively simple, it mostly depends on the server that you are using, and authentication method (if any). The HTTP authentication method is controlled with the CURLOPT_PROXYAUTH option, the default method is CURLAUTH_BASIC – if the proxy requires authentication, a username and password can be set in the [username]:[password] format, using the CURLOPT_PROXYUSERPWD option.

For now we'll just focus on using a proxy that doesn't require any authentication. Setting a proxy server and a port number in PHP for cURL can be done using the CURLOPT_PROXY option, like shown in the below example:

curl_setopt($ch, CURLOPT_PROXY, '128.0.0.3:8080');

As shown in the above example, you can set the a proxy with the IP:PORT syntax in PHP using cURL. But if you prefer to keep the ip seperated from the port, you can also use the CURLOPT_PROXYPORT option, which would result in the below PHP code:

Setting cURL Proxy Type

cURL supports two proxy types, the default is HTTP, and the other option is SOCKS5. You can set the proxy type using the CURLOPT_PROXYTYPE option. I.e.

curl_setopt($ch, CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5);

You really only need to set the type of the proxy, if you are not using a HTTP proxy.

Setting Authentication Method

As mentioned in the beginning of the tutorial, setting the authentication method of a proxy server can be done using the CURLOPT_HTTPAUTH option. To make this work properly, we will also need to provide a username and password for the proxy server, this is all accomplished in the below script, in which we are just using a BASIC authentication method.