Why Doesn't File_Get_Contents Work

file_get_contents works but file_put_contents doesn't

As you can see from the manual page:

This function returns the number of bytes that were written to the file, or FALSE on failure.

You should check to make sure that the return value is not false:

if (file_put_contents($path, $cnt) === false) {
// handle error
}

However I would assume that the vast majority of cases are a lack of permissions to write to the file. Fortunately PHP has a function to check that:

if (!is_writable($path)) {
// No permission to write
}

So, putting these two together you could do something like:

if (file_put_contents($path, $cnt) === false) {
if (!is_writable($path)) {
return "You do not have permission to write to $path";
}
return "An unknown error occurred while writing to $path";
}
return "successfully wrote to $path";

file_get_contents( ) not working

Login to your server via ssh and type

sudo nano /etc/php5/apache2/php.ini //<<<< ubuntu/debian server, might differ for you

in the file, simply press "ctrl + w" and type "allow_url_fopen" and Return, most probably you will come to the explanation first, so repeat the search a couple of times. Now you can change the entry from

allow_url_fopen=0

to

allow_url_fopen=1

press "ctrl + x" and confirm the file save with "y".

Then type

sudo service apache2 restart

This will restart apache so the new php.ini configuration can be loaded. After those steps, you should be able to use file_get_contents externally.


SIDENOTE

If you can't find your php.ini file, you will find the path to the loaded php.ini file in the top section of your phpinfo()

Sample Image

Why file_get_contents() doesn't work without protocol?

Since your script.php is wrapped in a function, you would include the file first and then use that function as your input data.

require_once(__DIR__ . '/../../out/script.php');
file_put_contents("../img/avatar/".$id.".jpg", MakeAvatar($id));


Related Topics



Leave a reply



Submit