duai5344 2015-06-18 20:58
浏览 27

使用代理时PHP cURL与file_get_contents

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条回答 默认 最新

  • dongsao8279 2015-06-18 21:02
    关注

    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

    评论

报告相同问题?

悬赏问题

  • ¥30 线性代数的问题,我真的忘了线代的知识了
  • ¥15 有谁能够把华为matebook e 高通骁龙850刷成安卓系统,或者安装安卓系统
  • ¥188 需要修改一个工具,懂得汇编的人来。
  • ¥15 livecharts wpf piechart 属性
  • ¥20 数学建模,尽量用matlab回答,论文格式
  • ¥15 昨天挂载了一下u盘,然后拔了
  • ¥30 win from 窗口最大最小化,控件放大缩小,闪烁问题
  • ¥20 易康econgnition精度验证
  • ¥15 msix packaging tool打包问题
  • ¥28 微信小程序开发页面布局没问题,真机调试的时候页面布局就乱了