代理之后的file_get_contents?

在工作中,我们必须使用代理来访问端口80,例如,我们为每个用户都有自己的自定义login。

我的临时解决方法是使用curl基本上通过代理login,并访问我需要的外部数据。

是否有某种先进的PHP设置,我可以设置,使内部每当它试图调用像file_get_contents()它总是通过代理? 我在Windows上自动取款机,所以如果这是唯一的方法,重新编译会很痛苦。

我的解决方法是暂时的原因是因为我需要一个通用的解决scheme,适用于多个用户,而不是使用一个用户的凭据(我曾考虑请求一个单独的用户帐户完全这样做,但密码经常变化,这种技术需要部署在整个十几个或更多的网站)。 我不想硬编码凭据基本上使用curl的解决方法。

要通过/不需要身份validation的代理使用file_get_content,应该这样做:

(我无法testing这个:我的代理需要authentication)

 $aContext = array( 'http' => array( 'proxy' => 'tcp://192.168.0.2:3128', 'request_fulluri' => true, ), ); $cxContext = stream_context_create($aContext); $sFile = file_get_contents("http://www.google.com", False, $cxContext); echo $sFile; 

当然,把我的代理服务器的IP和端口replace成适合你的那些;-)

如果你遇到这样的错误:

 Warning: file_get_contents(http://www.google.com) [function.file-get-contents]: failed to open stream: HTTP request failed! HTTP/1.0 407 Proxy Authentication Required 

这意味着你的代理需要authentication。

如果代理需要authentication,则必须添加几行代码,如下所示:

 $auth = base64_encode('LOGIN:PASSWORD'); $aContext = array( 'http' => array( 'proxy' => 'tcp://192.168.0.2:3128', 'request_fulluri' => true, 'header' => "Proxy-Authorization: Basic $auth", ), ); $cxContext = stream_context_create($aContext); $sFile = file_get_contents("http://www.google.com", False, $cxContext); echo $sFile; 

同样的事情关于IP和端口,这次也是login和密码;-)

现在,您将Proxy-Authorization标头传递给代理,包含您的login名和密码。

而…页面应显示;-)

希望这可以帮助 ! 玩的开心 !

使用stream_context_set_default函数。 使用起来更容易,因为您可以直接使用file_get_contents或类似的函数,而无需传递任何附加参数

这篇博文解释了如何使用它。 这是来自该页面的代码。

 <?php // Edit the four values below $PROXY_HOST = "proxy.example.com"; // Proxy server address $PROXY_PORT = "1234"; // Proxy server port $PROXY_USER = "LOGIN"; // Username $PROXY_PASS = "PASSWORD"; // Password // Username and Password are required only if your proxy server needs basic authentication $auth = base64_encode("$PROXY_USER:$PROXY_PASS"); stream_context_set_default( array( 'http' => array( 'proxy' => "tcp://$PROXY_HOST:$PROXY_PORT", 'request_fulluri' => true, 'header' => "Proxy-Authorization: Basic $auth" // Remove the 'header' option if proxy authentication is not required ) ) ); $url = "http://www.pirob.com/"; print_r( get_headers($url) ); echo file_get_contents($url); ?> 

取决于代理login的工作原理stream_context_set_default可能会对您有所帮助。

 $context = stream_context_set_default( array( 'http'=>array( 'header'=>'Authorization: Basic ' . base64_encode('username'.':'.'userpass') ) ) ); $result = file_get_contents('http://..../...'); 

这里有一个类似的post: http : //techpad.co.uk/content.php?sid=137它解释了如何做到这一点。

 function file_get_contents_proxy($url,$proxy){ // Create context stream $context_array = array('http'=>array('proxy'=>$proxy,'request_fulluri'=>true)); $context = stream_context_create($context_array); // Use context stream with file_get_contents $data = file_get_contents($url,false,$context); // Return data via proxy return $data; }