PHP cURL vs. file_get_contents when using proxy

1.4k views Asked by At

Running in Windows.

The following code works fine. I don't have specify a username and password when setting up the proxy.

$aContext = array(
'http' => array(
    'proxy' => 'tcp://ip:port', 
    'request_fulluri' => true,
),
);
$cxContext = stream_context_create($aContext);

echo file_get_contents("someurl", False, $cxContext);

However when I try this code it won't work unless I specify the username and password for the proxy.

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_PROTOCOLS, CURLPROTO_HTTP | CURLPROTO_HTTPS);
    curl_setopt($ch, CURLOPT_PROXY, 'http://ip:port');
    curl_setopt($ch, CURLOPT_URL, "someurl");
    $responseBody = curl_exec($ch);

I get an HTTP 407 error (Received HTTP code 407 from proxy after CONNECT) unless i specify the http://domain\user:password@ip:port

Any ideas how to make cURL work without specifying the user and password (like file_get_contents does)?

1

There are 1 answers

5
Elliot B. On

You can use the CURLOPT_PROXY and CURLOPT_PROXYPORT options:

curl_setopt($ch, CURLOPT_PROXY, "123.123.123.123");
curl_setopt($ch, CURLOPT_PROXYPORT, 8080);

It's unclear from your question, but if you need to use a username and password to authenticate with this proxy, then you can use the CURLOPT_PROXYUSERPWD option to specify your username and password and the CURLOPT_PROXYAUTH option to specify your authentication method:

curl_setopt($ch, CURLOPT_PROXYUSERPWD, "username:password");
curl_setopt($ch, CURLOPT_PROXYAUTH, CURLAUTH_BASIC); //HTTP Basic auth

Also, depending on what type of proxy you are working with, you may need to specify the type in the CURLOPT_PROXY setting or separately via CURLOPT_PROXYTYPE.

Documentation:

http://php.net/manual/en/function.curl-setopt.php

http://curl.haxx.se/libcurl/c/curl_easy_setopt.html