【问题标题】:If/else for https connection through proxy通过代理进行 https 连接的 if/else
【发布时间】:2017-05-24 08:49:17
【问题描述】:

我正在使用此代码检查代理服务器,然后再执行任何其他操作。当连接正常时,我有一个file_get_contents 线连接到一个网站。

$host = '123.45.678.90'; 
$port = 80; 
$waitTimeoutInSeconds = 1; 
if($fp = fsockopen($host,$port,$errCode,$errStr,$waitTimeoutInSeconds)){   
    $aContext = array(
    'http' => array(
    'proxy' => 'tcp://123.45.678.90:80',
    'request_fulluri' => true,
    ),
    );
    $cxContext = stream_context_create($aContext);

    // connect to website using a proxy server
    $file_content = file_get_contents('https://www.anything.com', False, $cxContext);
} else {
   // It didn't work 
} 
fclose($fp);

虽然代理连接成功,但我看到:警告 Cannot connect to HTTPS server through proxy?有没有机会有一个 if/else 语句,如果没有警告,我可以做某事,如果有警告,我可以停止做某事?我已经查看并搜索了很多,但没有找到任何我可以尝试的东西。

感谢您的帮助!

【问题讨论】:

  • phpinfo(); 显示了什么 OpenSSL 版本?
  • 它向我展示了 OpenSSL/1.0.1t
  • 你在windows上运行吗?
  • 不,我使用的是 Mac。
  • 您的 OpenSSl 版本似乎过时了,可能是问题的根源,请尝试更新它,apple.stackexchange.com/a/126832

标签: php if-statement proxy


【解决方案1】:

尝试使用curl而不是file_get_contents,它会起作用

<?php

$url = 'https://www.google.com';
// to check your proxy
// $url = 'http://whatismyipaddress.com/';
$proxy = '50.115.194.97:8080';

// create curl resource
$ch = curl_init();

// set options
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_PROXY, $proxy);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // read more about HTTPS     http://stackoverflow.com/questions/31162706/how-to-scrape-a-ssl-or-https-    url/31164409#31164409
curl_setopt($ch, CURLOPT_USERAGENT,'Mozilla/5.0 (Windows; U; Windows NT 5.1;     en-US; rv:1.8.1.13) Gecko/20080311 Firefox/2.0.0.13');

// $output contains the output string
$output = curl_exec($ch);

// close curl resource to free up system resources
curl_close($ch); 

echo $output;

?>

来自PHPhil

【讨论】:

  • 您的解决方案可能有效,但它不能解决 OP 的问题,或者对未来遇到相同问题的用户有任何价值。
  • file_get_contents() 是一个简单的螺丝刀。非常适合标头、HTTP 请求方法、超时、cookiejar、重定向和其他重要事项无关紧要的简单 GET 请求。带有 setopt 的 cURL 是一个具有几乎所有您能想到的选项的 powerdrills。
  • Puuuh,我对 cURL 真的很陌生。我不知道如何使用它或如何在其中获取 if/else。
  • 只需将 if 和 else 放在这一行 curl_setopt($ch, CURLOPT_PROXY, $proxy);
  • @vloryan 您的问题与OpenSSL 的过时版本有关,无论您使用cUrl 还是file_get_contents(),除非您设置CURLOPT_SSL_VERIFYPEER,否则它将不起作用到false,这是不安全
【解决方案2】:

if($fp = fsockopen($host,$port,$errCode,$errStr,$waitTimeoutInSeconds) 没有意义,如果这个代理正常工作,你可以简单地使用:

$aContext = array(
    'http' => array(
        'proxy' => 'tcp://123.45.678.90:80',
        'request_fulluri' => true,
    ),
);
$cxContext = stream_context_create($aContext);
$file_content = file_get_contents('https://google.com', False, $cxContext);
print $file_content;

【讨论】:

    猜你喜欢
    • 2018-12-01
    • 1970-01-01
    • 2010-10-05
    • 1970-01-01
    • 2014-04-11
    • 1970-01-01
    • 1970-01-01
    • 2011-07-12
    • 2014-08-13
    相关资源
    最近更新 更多