file_get_contents not working for local files

早过忘川 提交于 2019-11-30 15:58:05

问题


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.


回答1:


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.




回答2:


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.




回答3:


Solved this by using CURL. Here's the code. It will work with remote files e.g. http://yourdomain.com/file.ext

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, ''.$file_path_str.'');
curl_setopt($ch, CURLOPT_HTTPGET, 1);
curl_setopt ($ch, CURLOPT_HEADER, 0);
curl_setopt ($ch, CURLOPT_USERAGENT, sprintf("Mozilla/%d.0",rand(4,5)));
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_MAXREDIRS, 10);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

$curl_response_res = curl_exec ($ch);
curl_close ($ch);

I could not use @James solution because I'm using ob_start and ob_flush elsewhere in my code, so that would have messed things up for me.




回答4:


I recently solved this problem. On my windows machine it is acceptable to have spaces in your folder names. However PHP wasnt able to read this path.

I changed my folder name

From:

 C:\Users\JasonPC\Desktop\Jasons Work\Project

To:

 C:\Users\JasonPC\Desktop\JasonsWork\Project

Then PHP was able to read my files again.



来源:https://stackoverflow.com/questions/3457692/file-get-contents-not-working-for-local-files

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!