Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Capture error of php "file_get_contents" silently

Tags:

php

here is the code :

if( false == (file_get_contents($jsonaddress)))
{
    //error
    print ('Error with stream, getting file instead !<br />');
    $jsonaddress = 'listedesodeurs.txt';
} 

else 
{
    //noerror
    print ('Sucessfully GET data from JSON stream<br />');
    $jsoncontent = file_get_contents($jsonaddress);
    $size = file_put_contents('listedesodeurs.txt', $jsoncontent);
    echo ('Making backup of stream in file : '.round(($size/1024),0).' KB <br />');
}

When the file_get_contents = true (no error) everything get well when the file_get_contents = false I juste got THE big error message at screen... i just like to test it, not execute it !

HOW ?

here is the error message :

[function.file-get-contents]: failed to open stream: Inappropriate ioctl for device in 
like image 312
menardmam Avatar asked Nov 25 '25 22:11

menardmam


2 Answers

The quick way:

if( false == (@file_get_contents($jsonaddress)))

'@' suppresses errors.

A potentially better way is to just test:

if (! file_exists($jsonaddress)){

May well do you what you want (see if you can get get the stream, but simply return false if it fails)... but I'm not sure how well it will work. (haven't tried that with fopen wrappers recently)

like image 50
timdev Avatar answered Nov 28 '25 16:11

timdev


You can also check is_readable() to see if file_get_contents() is likely to fail:

if(is_readable($jsonaddress)) {
    // noerror
    print ('Sucessfully GET data from JSON stream<br />');
    ... etc
}
else {
    // error
    print ('Error with stream, getting file instead !<br />');
    ... etc
}
like image 32
too much php Avatar answered Nov 28 '25 17:11

too much php



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!