有时,无论出于何种原因,我们可能需要隐藏自己的 IP 地址。
隐藏 IP 的常用方法是使用代理服务器来处理 HTTP 请求。
设置浏览器以使用代理服务器很容易,但设置脚本和程序以使用代理可能需要更多的努力。
本教程将向我们展示如何让 PHP 脚本在使用 fread 和 file_get_contents 等函数执行 HTTP 请求时使用代理。
如果我们还记得上一教程中的示例,则可以像以下示例中演示的那样轻松地添加代理:
$sURL = "http://onitroad.com/Examples/ip.php"; //The Request URL $aHTTP['http']['proxy'] = 'tcp://127.0.0.1:8118'; //The proxy ip and port number $aHTTP['http']['request_fulluri'] = true; //use the full URI in the Request. for example:http://onitroad.com/Examples/ip.php $aHTTP['http']['method'] = 'GET'; $aHTTP['http']['header'] = "User-Agent: My PHP Script\r\n"; $aHTTP['http']['header'] .= "Referer: http://onitroad.com/\r\n"; $context = stream_context_create($aHTTP); $contents = file_get_contents($sURL, false, $context); echo 'Real IP:' . $_SERVER['REMOTE_ADDR'] . '<hr>'; echo 'Proxy IP:'. $contents;
与之前的教程一样,我们也可以使用本示例中提供的 URL 进行测试。
ip.php 是一个简单的 php 脚本,输出客户端的 IP。
如果这与我们自己的 IP 不同,则代理可以工作。
代理认证
如果我们使用的代理需要身份验证,我们只需添加代理授权 http 标头,其方式类似于上一个 php 教程中显示的方式。
登录到代理是通过组合用户名和密码来完成的,只用一个冒号“:”分隔,然后使用 base64 对其进行编码,并将其发送到 Proxy-Authorization http 标头中,如下例所示:
$sLogin = base64_encode('username:password'); $sURL = "http://onitroad.com/Examples/ip.php"; //The Request URL $aHTTP['http']['proxy'] = 'tcp://127.0.0.1:8118'; //The proxy ip and port number $aHTTP['http']['request_fulluri'] = true; //Use the full URI in the Request. for example:http://onitroad.com/Examples/ip.php $aHTTP['http']['method'] = 'GET'; $aHTTP['http']['header'] = "User-Agent: My PHP Script\r\n"; $aHTTP['http']['header'] .= "Referer: http://onitroad.com/\r\n"; $aHTTP['http']['header'] .= "Proxy-Authorization: Basic $sLogin"; $context = stream_context_create($aHTTP); $contents = file_get_contents($sURL, false, $context); echo 'Real IP:' . $_SERVER['REMOTE_ADDR'] . '<hr>'; echo 'Proxy IP:'. $contents;
日期:2020-06-02 22:15:57 来源:oir作者:oir