skip to Main Content

Problem

file_get_contents() is returning an empty string for some reason.

Code

index.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

My Research

Generally when file_get_contents("http://foo.com/somefile.txt") returns an empty string, it is due to one of two reasons

  1. somefile.txt is an empty file
  2. php.ini has allow_url_include = Off

$value should now be 69.00000000, but the function returns nothing.

Question

Why is $value empty after the function call?

2

Answers


  1. There are two different kinds of ’empty’. Either the file is actually 0 bytes long (empty string), or the call failed, and the return is FALSE. To quote the docs:

    On failure, file_get_contents() will return FALSE.

    Now, I don’t know why your call failed, but it’s likely to be logged in a webserver error log already, or you can convert these to exceptions to log them yourself.

    A third alternative, advisable on a development system, is to set display_errors in php.ini to make the problem visible:

    display_errors on
    

    This includes errors in the output, so that you can see them in the browser.

    Login or Signup to reply.
  2. 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;
        }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search