首页 > 解决方案 > 即使 allow_url_fopen = On,file_get_contents() 也会返回空

问题描述

问题

file_get_contents()由于某种原因返回一个空字符串。

代码

索引.php

<?php 
    $value = file_get_contents("http://foo.com/somefile.txt");
    echo $value;
?>

php.ini

allow_url_fopen = On
allow_url_include = On

http://foo.com/somefile.txt

69.00000000

我的研究

通常当file_get_contents("http://foo.com/somefile.txt")返回一个空字符串时,它是由于两个原因之一

  1. somefile.txt是一个空文件
  2. php.iniallow_url_include = Off

$value现在应该是69.00000000,但该函数不返回任何内容。

问题

为什么$value函数调用后为空?

标签: phpapachefileio

解决方案


try this:


checkRemote("http://foo.com/somefile.txt");

 function checkRemote($url)
{
    if(!checkRemoteLink($url)){
        echo 'bad link!';
    } else if(!checkRemoteFile($url)){
        echo 'bad file!';
    } else echo 'trouble!';
}

function checkRemoteLink($url)
{
    $file_headers = @get_headers($url);
    if (!$file_headers || $file_headers[0] == 'HTTP/1.1 404 Not Found') {
        return false;
    } else {
        return true;
    }
}

function checkRemoteFile($url)
{
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_NOBODY, 1);
    curl_setopt($ch, CURLOPT_FAILONERROR, 1);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    if (curl_exec($ch) !== FALSE) {
        return true;
    } else {
        return false;
    }
}

推荐阅读