Search code examples
phpif-statementfile-get-contentsfile-exists

PHP if file_exists() statement fails on file_get_content() from URL


I have a very simple function to read URL image file and save it on server.

function o99_download_shot_binary(){

        $url = esc_url_raw( o99_get_content_link() ); // function returns http:// url
        $img = $uploads['basedir'] . '/tmp/' . uniqid() . '.jpeg'; // name and location
        file_put_contents($img, file_get_contents($url)); 
    }

IT works ok, but sometimes , o99_get_content_link() returns an invalid URL, so an empty image is saved , so I made a simple check with if statement and separated the one liner:

function o99_download_shot_binary(){

    $url = esc_url_raw( o99_get_content_link() ); // function returns http:// url
    $img = $uploads['basedir'] . '/tmp/' . uniqid() . '.jpeg'; // name and location
    $file = file_get_contents($url);
     if (file_exists($file)) {
        file_put_contents($img, $file); 
     }
}

But doing so, NO image is saved .

So I tried to change the if statement to

if ( $file) { file_put_contents($img, $file); }

..and now it works .

As everything is OK now, you might be wondering why did I posted this question , well, since I want also to UNDERSTAND what I am doing - My Question is simply :

why does the file_exists($file) check fails ?

I assumed to myself (maybe wrongly) that it is because the file_exists() only checks LOCAL filesystem. If this is the case , then is there a dedicated function to check the existence over URL ? or any other better solutions for future references ?

EDIT I (as per comments request )

Var_dump() is a binary string :

string(51238) "����JFIF��������BZ�|su��{��3�_�R��[J��z���K�^��g�/��9���|*�F��W~�>񏎭tχ�>��� �&��?�~0�f�����[��i���R��_���g~�_��Ɵ�#����.5�x+�_ u��-�ٿ�L����ƺV��  ... ... ... 

But this is predictable, like I said in original question, the file IS being saved OK, it is just a question of WHY the file_exists() check fails, and if there is a better way to perform that check on a binary remote file from URL...


Solution

  • file_exists() expects a path, like /home/user/foo.txt, or C:\foo.txt. You are supplying it with the contents of the file, not the local path to the file, so it will not return a true value (unless, of course, the contents of the file are a valid file path to an existing file... not to muddy the waters but it had to be said :) ).