代理后面的 file_get_contents ?

2021-12-31 00:00:00 proxy php

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

At work we have to use a proxy to basically access port 80 for example, we have our own custom logins for each user.

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

My temporary workaround is using curl to basically login as myself through a proxy and access the external data I need.

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

Is there some sort of advanced php setting I can set so that internally whenever it tries to invoke something like file_get_contents() it always goes through a proxy? I'm on Windows ATM so it'd be a pain to recompile if that's the only way.

我的解决方法是临时的原因是因为我需要一个通用的解决方案,适用于多个用户,而不是使用一个用户的凭据(我曾考虑请求一个单独的用户帐户来单独执行此操作,但密码经常更改,并且此技术需要部署在十几个或更多站点中).我不想硬编码凭据基本上是为了使用 curl 解决方法.

The reason my workaround is temporary is because I need a solution that's generic and works for multiple users instead of using one user's credentials ( Ive considered requesting a separate user account solely to do this but passwords change often and this technique needs to be deployed throughout a dozen or more sites ). I don't want to hard-code credentials basically to use the curl workaround.

推荐答案

使用 file_get_contents() 通过/通过不需要身份验证的代理,应该这样做:

To use file_get_contents() over/through a proxy that doesn't require authentication, something like this should do :

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

$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 和端口替换为适合您的 IP 和端口;-)

Of course, replacing the IP and port of my proxy by those which are OK for yours ;-)

如果您遇到这种错误:

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

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

It means your proxy requires an authentication.

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

If the proxy requires an authentication, you'll have to add a couple of lines, like this :

$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 和端口的同样的事情,这一次,还有登录和密码;-) 查看所有有效的 http 选项.

Same thing about IP and port, and, this time, also LOGIN and PASSWORD ;-) Check out all valid http options.

现在,您正在传递一个代理授权 代理的标头,包含您的登录名和密码.

Now, you are passing an Proxy-Authorization header to the proxy, containing your login and password.

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

And... The page should be displayed ;-)

相关文章