Why doesn't file_get_contents work?
Asked Answered
C

6

15

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>
Corycorybant answered 17/7, 2011 at 14:28 Comment(4)
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?Malayopolynesian
what's the output of ini_get('allow_url_open')?Libradalibrarian
#4761904 As maps.googleapis.com/maps/api/geocode/… is JSON why not try the approach suggested in the link above, using cURL?Wales
For future readers of these comments, I think @Libradalibrarian meant to ask what the output of ini_get('allow_url_fopen') was. It's worth checking whether it is set or not.Mm
M
32

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.

Mamoun answered 17/7, 2011 at 14:28 Comment(15)
<?php, wouldn't matter much on the behavior of gile_get_contents().Dayle
@Shamim but it would matter for the whole script when short open tags are disabledLibradalibrarian
@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.Mamoun
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 <?php will always work, whereas <? might not. So I think it's a OK answer.Malayopolynesian
@Mark Tomlin: This answer is a community wiki, feel free to add your thoughts (if not covered yet).Mamoun
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.Belshazzar
Yeah, I'll merge my answer into this.Malayopolynesian
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 :)Mamoun
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.Corycorybant
ehm, isn't ~ a bit operator and ~0 == -1?Nitrosamine
@superhero: Yes and yes, see 3v4l.org/kUORP - also - is an arithmetic operator.Mamoun
I guess my question would be, why go the "long way" (not very long ofc) instead of just typing -1 from the beginning? @Mamoun I'm guessing there's no reason, but if so; I'm keen to know :)Nitrosamine
I'm sorry if this caused any confusion. Use -1 or ~0 both should be interchangeable for the bitmask.Mamoun
The Google Maps API test code should be replaced with something a little less complex/less likely to break, since it's currently broken.Grope
@HashimAziz: Yes, good idea. Probably while you already know that it's broken, do you by chance also know a good JSON result? We could then replace the URL with a data:// URI encoding that JSON.Mamoun
P
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.

Protrusive answered 1/10, 2013 at 16:56 Comment(0)
B
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

Bifilar answered 23/1, 2014 at 0:47 Comment(0)
D
2

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

Divisible answered 15/11, 2012 at 18:34 Comment(2)
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()Impanel
@Impanel I just read the docs and that is not a limitation of file_get_contents(). 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.Divisible
U
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>
Unaware answered 19/12, 2012 at 15:18 Comment(1)
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.Prestigious
G
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.

Grangerize answered 24/2, 2021 at 13:13 Comment(2)
This is dangerous, you should only use 775 in most cases.Gerhard
i have changed that and my point is that the permission may be the problemGrangerize

© 2022 - 2024 — McMap. All rights reserved.