php 将代理与 file_get_contents 一起使用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14535197/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Using proxy with file_get_contents
提问by Jinu Joseph Daniel
I am getting data for my application from a website, say x.com. I use the php function file_get_contents() to fetch the data. It is sure that , my server's ip address will be shown in x.com 's logs. Is there any way to hide my server's ip without using proxy?
我正在从一个网站获取我的应用程序的数据,比如 x.com。我使用 php 函数 file_get_contents() 来获取数据。可以肯定的是,我的服务器的 IP 地址将显示在 x.com 的日志中。有没有办法在不使用代理的情况下隐藏我的服务器的 ip?
If I have a proxy ,how to use it with file_get_contents()?
如果我有代理,如何将它与 file_get_contents() 一起使用?
I need to send the request in both HTTP POST and HTTP GET methods
我需要在 HTTP POST 和 HTTP GET 方法中发送请求
回答by farmer1992
test.php using http://ifconfig.me/ip
test.php 使用http://ifconfig.me/ip
code modified from http://www.php.net/manual/en/function.file-get-contents.php
修改自http://www.php.net/manual/en/function.file-get-contents.php 的代码
<?php
// Create a stream
$opts = array(
'http'=>array(
'method'=>"GET",
'header'=>"Accept-language: en\r\n" .
"Cookie: foo=bar\r\n",
'proxy' => 'tcp://221.176.14.72:80',
)
);
$context = stream_context_create($opts);
// Open the file using the HTTP headers set above
$file = file_get_contents('http://ifconfig.me/ip', false, $context);
var_dump($file);
回答by Jon Weers
Definitely agree with farmer1992.
绝对同意farmer1992。
For anyone having issues with file_get_contentsover SSL + proxy, there is a known bug with PHP's stream_context_create:
对于file_get_contents通过 SSL + 代理遇到问题的任何人,PHP 的 stream_context_create 存在一个已知错误:
https://bugs.php.net/bug.php?id=63519
https://bugs.php.net/bug.php?id=63519
Fortunately, the workaround is simple. Basically, the context creator gets confused when parsing an "https" target URL to both the proxy and SSL configs. You just have to set the SNI_server_namein the SSL config:
幸运的是,解决方法很简单。基本上,上下文创建者在将“https”目标 URL 解析为代理和 SSL 配置时会感到困惑。您只需要在 SSL 配置中设置SNI_server_name:
$targetUrl = "https://something.com";
$sniServer = parse_url($targetUrl, PHP_URL_HOST);
$params = array('your'=>'post','params'=>'here');
$ctxConfig = array(
'http' => array(
'method' => 'POST',
'header' => 'Content-type: application/x-www-form-urlencoded'."\r\n",
'content' => http_build_query($params),
'proxy' => 'tcp://12.34.56.78:3128',
'request_fulluri' => true
),
'ssl' => array(
'SNI_enabled' => true,
'SNI_server_name' => $sniServer
)
);
$context = stream_context_create($ctxConfig);
file_get_contents($targetUrl,false,$context)
Hopefully that saves someone some time!
希望这可以节省一些时间!

