php: file_get_contents returns 空字符串

php: file_get_contents returns empty string

我正在尝试使用 file_get_contents 函数在屏幕上打印图像 url 的内容:

<?php
$image2 = "http://www.example.com";
echo file_get_contents( $image2 );
?>

当运行时,页面加载大约需要 15-20 秒,然后什么都不显示。我还尝试使用 cURL,结果相同。有人对如何解决此问题有任何建议吗?

这是我试过的 curl 代码:

<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,"http://www.example.com");
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
$contents=curl_exec($ch);
curl_close($ch);
echo $contents;
?>

当运行时,页面一直加载直到服务器取消请求。

file_get_contents like many PHP functions, returns false in case of failure. false is not echoed 到输出,这就是为什么你看不到任何东西,就好像回显了一个空字符串。

将结果存储在变量中,并用===运算符检查错误。

$file = file_get_contents($image2);
if ($file === false) {
  // Check the error and handle as you like.
} else {
  echo $image2;
}

不幸的是,这只会告诉您是否有错误,但不会告诉您是哪一个。幸运的是,您也使用了 cUrl。还有 curl_errorcurl_errno,您可以使用它们来获取错误本身的更详细描述。通常这会立即解决问题。

此时我的怀疑:通常我会认为file_get_contents的失败与allow-url-fopen的设置有关,但现在,20秒的延迟,以及cUrl显示的事实同样的行为,表明你可能会超时。可能是您的防火墙不允许您执行这样的请求。

鉴于您提到您的脚本 运行 在免费主机服务器上。

大多数免费托管服务器都禁用了 file_get_contents() 功能。检查免费托管服务器的帮助部分,我非常有信心那里会提到它已被禁用。