[php] Why doesn't file_get_contents work?

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>

This question is related to php geocoding file-get-contents

The answer is


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


//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>

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 777 file.jpeg

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


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


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);

print '<p>', var_dump($jsonData), '</p>';

# 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 $jsonData;
}

?>
    </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.


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.


Examples related to php

I am receiving warning in Facebook Application using PHP SDK Pass PDO prepared statement to variables Parse error: syntax error, unexpected [ Preg_match backtrack error Removing "http://" from a string How do I hide the PHP explode delimiter from submitted form results? Problems with installation of Google App Engine SDK for php in OS X Laravel 4 with Sentry 2 add user to a group on Registration php & mysql query not echoing in html with tags? How do I show a message in the foreach loop?

Examples related to geocoding

This API project is not authorized to use this API. Please ensure that this API is activated in the APIs Console Create or update mapping in elasticsearch Getting distance between two points based on latitude/longitude Measuring the distance between two coordinates in PHP Why doesn't file_get_contents work? How can I get city name from a latitude and longitude point? Calculating Distance between two Latitude and Longitude GeoCoordinates Given the lat/long coordinates, how can we find out the city/country? Google Maps: how to get country, state/province/region, city given a lat/long value? Get latitude and longitude based on location name with Google Autocomplete API

Examples related to file-get-contents

file_get_contents(): SSL operation failed with code 1, Failed to enable crypto get url content PHP PHP cURL vs file_get_contents Does file_get_contents() have a timeout setting? JSON to PHP Array using file_get_contents Why doesn't file_get_contents work? Get file content from URL? Show image using file_get_contents Alternative to file_get_contents? PHP ini file_get_contents external url