【问题标题】:Connect to https server with PHP使用 PHP 连接到 https 服务器
【发布时间】:2014-04-06 10:38:55
【问题描述】:

我需要从使用 https 协议(即https://site.com/page)的服务器上的网页获取数据。这是我一直在使用的 PHP 代码:

$POSTData = array('');
$context = stream_context_create(array(
    'http' => array(
    //'ignore_errors' => true,
    'user_agent' => "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1500.95 Safari/537.36",
    'header' => "User-Agent: Mozilla/5.0 (Macintosh; U; Intel Mac OS X; en) AppleWebKit/522.11.1 (KHTML, like Gecko) Version/3.0.3 Safari/522.12.1",
    'request_fulluri' => true,
    'method'  => 'POST',
    'content' => http_build_query($POSTData),
    )
));
$pageHTML = file_get_contents("https://site.com/page", FALSE, $context);
echo $pageHTML;

但是,这似乎不起作用,发出警告:file_get_contents 没有关于错误的信息。可能是什么情况,如何解决它以连接到服务器并获取页面?

编辑:感谢所有回答的人,我的问题是我使用的是 HTTP 代理,我从代码中删除了它,以免让您感到困惑,因为我认为这不可能是问题所在。为了让代码通过 HTTP 代理加载 HTTPS 页面,我修改了我使用的 stream_context_create,如下所示:

    stream_context_create(array(
    'https' => array(
    //...etc

【问题讨论】:

  • 错误信息的具体内容是什么?

标签: php https file-get-contents


【解决方案1】:

Have a look at cURL 如果您还没有的话。使用 cURL,您可以远程访问网页/API/文件并将其下载到您的服务器。 curl_setopt() 函数允许您指定是否验证远程服务器的证书

$file = fopen("some/file/directory/file.ext", w);
$ch   = curl_init("https://site.com/page");
curl_setopt($ch, CURLOPT_FILE, $file);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); //false to disable the cert check if needed

$data = curl_exec($ch);
curl_close($ch);
fclose($file);

类似的东西可以让你连接到 HTTPS 服务器,然后下载你想要的文件。如果您知道服务器有一个有效的证书(即您不是在没有有效证书的服务器上开发),那么您可以省略curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); 行,因为默认情况下cURL 将尝试验证证书。

cURL 还有the curl_getinfo() function,它将为您提供有关最近处理的传输的详细信息,这将有助于您调试程序。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-07-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-29
    • 2020-06-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多