13

Why does file_get_contents not work for me? In the test file code below, it seems that everyone's examples that I've searched for all have this function listed, but it never gets executed. Is this a problem with the web hosting service? Can someone test this code on their server just to see if the geocoding array output actually gets printed out as a string? Of course, I am trying to assign the output to a variable, but there is no output here in this test file....

<html>
<head>        
<title>Test File</title>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"> 
</script>
</head>
<body>
<?    
$adr = 'Sydney+NSW';
echo $adr;
$url = "http://maps.googleapis.com/maps/api/geocode/json?address=$adr&sensor=false";
echo '<p>'.$url.'</p>';
echo file_get_contents($url);
print '<p>'.file_get_contents($url).'</p>';
$jsonData   = file_get_contents($url);
echo $jsonData;
?>
</body>
</html>
hakre
  • 193,403
  • 52
  • 435
  • 836
PVJAZZ
  • 139
  • 1
  • 1
  • 3
  • 1
    What is the error message your getting? Are you getting an error message at all? It the whole page returning, and just failing to produce the output you want? – Mark Tomlin Jul 17 '11 at 14:29
  • 3
    what's the output of `ini_get('allow_url_open')`? – Gordon Jul 17 '11 at 14:32
  • http://stackoverflow.com/questions/4761404/why-does-phps-file-get-contents-incorrectly-retrieve-json-files-from-xkcd As http://maps.googleapis.com/maps/api/geocode/json?address=Sydney+NSW&sensor=false is JSON why not try the approach suggested in the link above, using cURL? – sdolgy Aug 05 '11 at 10:17
  • 4
    For future readers of these comments, I think @Gordon meant to ask what the output of `ini_get('allow_url_fopen')` was. It's worth checking whether it is set or not. – Joundill Aug 24 '16 at 06:55

6 Answers6

31

Check file_get_contents PHP Manual return value. If the value is FALSE then it could not read the file. If the value is NULL then the function itself is disabled.

To learn more what might gone wrong with the file_get_contents operation you must enable error reporting and the display of errors to actually read them.

# Enable Error Reporting and Display:
error_reporting(~0);
ini_set('display_errors', 1);

You can get more details about the why the call is failing by checking the INI values on your server. One value the directly effects the file_get_contents function is allow_url_fopen. You can do this by running the following code. You should note, that if it reports that fopen is not allowed, then you'll have to ask your provider to change this setting on your server in order for any code that require this function to work with URLs.

<html>
    <head>        
        <title>Test File</title>
        <script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false">
        </script>
    </head>
    <body>
<?php

# Enable Error Reporting and Display:
error_reporting(~0);
ini_set('display_errors', 1);

$adr = 'Sydney+NSW';
echo $adr;
$url = "http://maps.googleapis.com/maps/api/geocode/json?address=$adr&sensor=false";
echo '<p>', $url, '</p>';

$jsonData = file_get_contents($url);

echo '<pre>', htmlspecialchars(substr($jsonData, 128)), sprintf(' ... (%d)', strlen((string)$jsonData)), '</pre>';

# Output information about allow_url_fopen:
if (ini_get('allow_url_fopen') == 1) {
    echo '<p style="color: #0A0;">fopen is allowed on this host.</p>';
} else {
    echo '<p style="color: #A00;">fopen is not allowed on this host.</p>';
}


# Decide what to do based on return value:
if ($jsonData === FALSE) {
    echo "Failed to open the URL ", htmlspecialchars($url);
} elseif ($jsonData === NULL) {
   echo "Function is disabled.";
} else {
   echo '<pre>', htmlspecialchars($jsonData), '</pre>';
}

?>
    </body>
</html>

If all of this fails, it might be due to the use of short open tags, <?. The example code in this answer has been therefore changed to make use of <?php to work correctly as this is guaranteed to work on in all version of PHP, no matter what configuration options are set. To do so for your own script, just replace <? or <?php.

hakre
  • 193,403
  • 52
  • 435
  • 836
  • 2
    @Shamim but it would matter for the whole script when short open tags are disabled – Gordon Jul 17 '11 at 14:36
  • 2
    @Shamim Hafiz: It does matter a whole lot as this can make the difference between being executed or not. It is not executed if the server has disabled [`short_open_tag`](http://php.net/manual/en/ini.core.php). – hakre Jul 17 '11 at 14:36
  • 1
    That all depends really. Try to provide an answer that will cover all available configuration options. I think that this falls into the bracket myself, as ` – Mark Tomlin Jul 17 '11 at 14:39
  • @Mark Tomlin: This answer is a community wiki, feel free to add your thoughts (if not covered yet). – hakre Jul 17 '11 at 14:47
  • 1
    It's a great answer. It seems to cover _all_ the reasons that the OP's code might be failing, and tells him/her how to debug the function call. If the function call ends up returning `NULL`, then he/she may go away and figure out _why_ this may be... with Mark Tomlin's answer's help, I'm sure. – Lightness Races in Orbit Jul 17 '11 at 14:52
  • Yeah, I'll merge my answer into this. – Mark Tomlin Jul 17 '11 at 14:53
  • I'm not sure that if NULL is returned it means that allow url fopen is off. I think in case it is off, it will return false. So probably it should just be displayed for information before calling the function so it's a no-brainer :) – hakre Jul 17 '11 at 15:13
  • 1
    Ok, great thanks. Being new at this, and with a bit more research from your hints here, I was using an account with Yahoo! web hosting, and they stated that they stated it was against their security risks to set allow_url_fopen to "On", or change any other items in the php.ini file. So... leaving Yahoo! and heading over to Joomla web hosting... thanks for all your help. – PVJAZZ Jul 17 '11 at 22:41
  • ehm, isn't `~` a bit operator and `~0` == `-1`? – superhero Jun 19 '17 at 13:28
  • @superhero: Yes and yes, see https://3v4l.org/kUORP - also `-` is an arithmetic operator. – hakre Jun 19 '17 at 13:49
  • I guess my question would be, why go the "long way" (not very long ofc) instead of just typing `-1` from the beginning? @hakre I'm guessing there's no reason, but if so; I'm keen to know :) – superhero Jun 19 '17 at 14:24
  • I'm sorry if this caused any confusion. Use -1 or ~0 both should be interchangeable for the bitmask. – hakre Jun 19 '17 at 15:08
6

If PHP's allow_url_fopen ini directive is set to true, and if curl doesn't work either (see this answer for an example of how to use it instead of file_get_contents), then the problem could be that your server has a firewall preventing scripts from getting the contents of arbitrary urls (which could potentially allow malicious code to fetch things).

I had this problem, and found that the solution for me was to edit the firewall settings to explicitly allow requests to the domain (or IP address) in question.

Community
  • 1
  • 1
Nick F
  • 9,781
  • 7
  • 75
  • 90
4

If it is a local file, you have to wrap it in htmlspecialchars like so:

    $myfile = htmlspecialchars(file_get_contents($file_name));

Then it works

Stefan Gruenwald
  • 2,582
  • 24
  • 30
2

Wrap your $adr in urlencode(). I was having this problem and this solved it for me.

YakovL
  • 7,557
  • 12
  • 62
  • 102
Michael J. Calkins
  • 32,082
  • 15
  • 62
  • 91
  • You might want to be careful with this approach because `urlencode()` will make your eventual address longer and might exceed the maximum length allowed by `file_get_contents()` – Hussam Sep 27 '13 at 08:25
  • @Hussam I just read the docs and that is not a limitation of `file_get_contents()`. http://php.net/manual/en/function.file-get-contents.php Only browsers when you type it in the address bar, but even then you'd have to write 2kb to 4kb to break that max. – Michael J. Calkins Sep 27 '13 at 15:09
1
//JUST ADD urlencode();
$url = urlencode("http://maps.googleapis.com/maps/api/geocode/json?address=$adr&sensor=false");
<html>
<head>        
<title>Test File</title>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"> 
</script>
</head>
<body>
<?php    
$adr = 'Sydney+NSW';
echo $adr;
$url = "http://maps.googleapis.com/maps/api/geocode/json?address=$adr&sensor=false";
echo '<p>'.$url.'</p>';
echo file_get_contents($url);
print '<p>'.file_get_contents($url).'</p>';
$jsonData   = file_get_contents($url);
echo $jsonData;
?>
</body>
</html>
Rameez SOOMRO
  • 1,529
  • 15
  • 24
  • 3
    What horrible code! PHP mixed with HTML and opening PHP short tags. This will break and confuse new people. Yes I know it's from 2012. – Branndon May 18 '17 at 22:30
0

The error may be that you need to change the permission of folder and file which you are going to access. If like GoDaddy service you can access the file and change the permission or by ssh use the command like:

sudo chmod 775 file.jpeg

and then you can access if the above mentioned problems are not your case.

Nadeem
  • 53
  • 12