代理后面的file_get_contents?

med*_*iev 71 php proxy

在工作中,我们必须使用代理基本上访问端口80,例如,我们为每个用户都有自己的自定义登录.

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

是否有某种高级的PHP设置我可以设置,以便在内部尝试调用像file_get_contents()它总是通过代理的东西?我在Windows ATM上,如果这是唯一的方法,重新编译会很痛苦.

我的解决方法是临时的原因是因为我需要一个通用的解决方案,适用于多个用户,而不是使用一个用户的凭据(我考虑过单独请求一个单独的用户帐户,但密码经常更改,并且需要在整个十几个或更多的网站).我不想硬编码凭证基本上使用curl解决方法.

Pas*_*TIN 164

要在不需要身份验证的代理上使用file_get_content,这样的事情应该:

(我无法测试这个:我的代理需要身份验证)

$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;
Run Code Online (Sandbox Code Playgroud)

当然,替换我的代理的IP和端口的那些对你来说是好的;-)

如果你遇到这种错误:

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
Run Code Online (Sandbox Code Playgroud)

这意味着您的代理需要身份验证.

如果代理需要身份验证,则必须添加几行,如下所示:

$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;
Run Code Online (Sandbox Code Playgroud)

关于IP和端口也一样,这次也是LOGIN和PASSWORD ;-)

现在,您将代理授权标头传递给代理,其中包含您的登录名和密码.

并且......应该显示页面;-)


小智 22

使用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);
?>
Run Code Online (Sandbox Code Playgroud)