首页 > 解决方案 > file_get_contents() 返回空字符串,启用 allow_url_fopen

问题描述

file_get_contents() 返回空字符串,即使所需的所有扩展和功能似乎都已启用。

我已经解决了所有类似的问题并尝试了他们的修复但没有成功。我没有收到任何错误,我尝试了多个远程和本地 URL。

<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);

try {
echo "HTML: <br>";
$html=file_get_contents("https://www.google.co.uk");
var_dump($html);

echo "<hr><br>";

if( ini_get('allow_url_fopen') ) {
echo "allow_url_fopen() exists";
}
else {
echo "allow_url_fopen() does not exist";
}


echo "<br>";
if (function_exists('file_get_contents')) {
echo "file_get_contents() exists";
}
else {
echo "file_get_contents() does not exist";
}



echo "<br>";
$w = stream_get_wrappers();
echo 'openssl: ',  extension_loaded  ('openssl') ? 'yes':'no', "<br>";
echo 'http wrapper: ', in_array('http', $w) ? 'yes':'no', "<br>";
echo 'https wrapper: ', in_array('https', $w) ? 'yes':'no', "<br>";
echo 'wrappers: ', var_export($w);

echo "<br>";
if( ini_get('allow_url_include') ) {
echo "allow_url_include() exists";
}
else {
echo "<font style='color:red;'>allow_url_include() does not exist</font>";
}

echo "<br>";
if (!extension_loaded('openssl')) {
    echo "<font style='color:red;'>openssl does not exist</font>";
}
else {
    echo "openssl exists";
}

} catch (Exception $e) {
    var_dump($e);
}

页面返回:

HTML: 
string(0) ""

allow_url_fopen() exists
file_get_contents() exists
openssl: yes
http wrapper: yes
https wrapper: yes
wrappers: array ( 0 => 'compress.zlib', 1 => 'compress.bzip2', 2 => 'dict', 3 => 'ftp', 4 => 'ftps', 5 => 'gopher', 6 => 'http', 7 => 'https', 8 => 'imap', 9 => 'imaps', 10 => 'ldap', 11 => 'ldaps', 12 => 'pop3', 13 => 'pop3s', 14 => 'rtsp', 15 => 'smb', 16 => 'smbs', 17 => 'smtp', 18 => 'smtps', 19 => 'telnet', 20 => 'tftp', 21 => 'php', 22 => 'file', 23 => 'glob', 24 => 'data', 25 => 'phar', 26 => 'zip', )
allow_url_include() exists
openssl exists

我也试过 chmod 777 和 755。

我不能使用 cURL,因为 file_get_contents() 是我将来要使用的框架的一部分。

标签: php

解决方案


像这样试试

  <?php
    $url = 'https://www.google.co.uk';
    $ch = curl_init();

    curl_setopt($ch, CURLOPT_AUTOREFERER, TRUE);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);

    $data = curl_exec($ch);
    curl_close($ch);
    echo '<pre>';
    var_dump($data);
    echo '</pre>';
    // Close handle

    ?>

推荐阅读