How to use CURL with Proxy
This post will be demonstrating how to use curl with proxy in PHP and Linux command line. What is additional parameter we need to pass while using curl via proxy. So I am starting with proxy configuration in PHP curl.
1) PHP curl with proxy
$url = 'http://localhost/path/to/file.php'; $proxy = '127.0.0.2:3128'; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_PROXY, $proxy); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE); curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); curl_setopt($ch, CURLOPT_HEADER, TRUE); $result = curl_exec($ch); curl_close($ch); echo $result;
Please add CURLOPT_PROXYUSERPWD If you configured proxy with credentials.
curl_setopt($ch, CURLOPT_PROXYUSERPWD, "username:password");
CURLOPT_URL | The URL to fetch. This can also be set when initializing a session with curl_init(). |
CURLOPT_PROXY | The HTTP proxy to tunnel requests through. |
CURLOPT_FOLLOWLOCATION | TRUE to follow any “Location: ” header that the server sends as part of the HTTP header |
CURLOPT_RETURNTRANSFER | TRUE to return the transfer as a string of the return value of curl_exec() instead of outputting it out directly. |
CURLOPT_HEADER | TRUE to include the header in the output. |
CURLOPT_PROXYUSERPWD | A username and password formatted as “[username]:[password]” to use for the connection to the proxy |
2) Proxy In linux Command Line:
Syntax: curl <URL> --proxy <PROXY_HOST>:<PROXY_PORT> curl http://localhost/project/file.jpg --proxy http://127.0.0.1:3128
In Linux we have also the capability to configure different proxy through environment variables like http_proxy, ftp_proxy and https_proxy.
export http_proxy=http://127.0.0.2:3128 #for password protected proxy export http_proxy=http://user:password@127.0.0.2:3128 #to support https url export https_proxy=http://127.0.0.2:3128
(Visited 1,732 times, 75 visits today)