如何让PHP使用代理设置连接到互联网?

Ale*_*xar 25 php proxy

我是一个不允许直接连接到互联网的代理服务器.我的所有PHP应用程序都无法连接到Internet进行更新检查等.

如何告诉PHP我的代理设置?

我不想在代码中输入代理设置,我希望PHP本身通过全局配置设置或类似的方式使用它.

Ian*_* Hu 14

如果几乎所有的互联网访问都需要代理,我宁愿这样做.

//add this as the first line of the entry file may it is the index.php or config.php
stream_context_set_default(['http'=>['proxy'=>'proxy-host:proxy-port']]);
Run Code Online (Sandbox Code Playgroud)

代理将工作file_get_contents但不工作curl_exec

这是一份官方文件.

  • @Tarik如果您的代理服务器需要基本身份验证,您需要这样做`stream_context_set_default(['http'=> ['proxy'=>'proxy-host:proxy-port','header'=>'代理服务器) -Authorization:Basic'.base64_encode('your-username:your-password')]]);` (2认同)

Tra*_*mov 9

这取决于您的PHP应用程序如何连接到Internet.

如果使用PHP cUrl采取最可能的情况.在这种情况下,以下选项将帮助您:

curl_setopt($handle, CURLOPT_PROXY, $proxy_url); 
curl_setopt($handle, CURLOPT_PROXYUSERPWD, "[username]:[password]"); 
Run Code Online (Sandbox Code Playgroud)

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


Eva*_*Lee 6

示例代码:

function getUrl($url)
{
    $ch = curl_init(); 
    $timeout = 5; // set to zero for no timeout 
    curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout); 
    curl_setopt ($ch, CURLOPT_URL, $url); 
    curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1); 
    curl_setopt($ch, CURLOPT_PROXY, "http://proxy.example.com"); //your proxy url
    curl_setopt($ch, CURLOPT_PROXYPORT, "8080"); // your proxy port number 
    curl_setopt($ch, CURLOPT_PROXYUSERPWD, "username:pass"); //username:pass 
    $file_contents = curl_exec($ch); 
    curl_close($ch); 
    return $file_contents;
}

echo  getUrl("http://www.google.com");
Run Code Online (Sandbox Code Playgroud)