Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

file_get_contents not working for local files

I recently upgraded my XAMPP from PHP 5.2 to 5.3.1

I seem to be having a problem with file_get_contents().

I can use the function to get something like "http://www.google.com", but it times out when I use it on a domain I have setup locally e.g. "http://localhost/my_dir/my_css_file.css".

I'm not really sure what the problem is. If it's a bug, is there a viable alternative?

Kindly advise.

like image 401
ObiHill Avatar asked Feb 26 '23 12:02

ObiHill


2 Answers

Try to use include() instead of file_get_contents().

<?php include($_SERVER['HTTP_HOST'] . "/my_dir/my_css_file.css"); ?>

or

<?php include($_SERVER['DOCUMENT_ROOT'] . "/my_dir/my_css_file.css"); ?>

Updates corresponding your comments:

$string = get_include_contents('somefile.php');

function get_include_contents($filename) {
    if (is_file($filename)) {
        ob_start();
        include $filename;
        $contents = ob_get_contents();
        ob_end_clean();
        return $contents;
    }
    return false;
}

This will get file data into variable $string.

like image 178
James Avatar answered Mar 07 '23 05:03

James


Any chance you're on a Windows system? There is a bug in a combination of Windows, file_get_contents and localhost which is not going to be fixed. See Bug 38826 and Bug 40881

Try using 127.0.0.1 instead of localhost or set up any different domain name. Then you should get it working.

like image 45
sprain Avatar answered Mar 07 '23 05:03

sprain