0

I'm using file_get_contents() along with file_put_contents() to download some files.

I'm using as everyone suggests:

$file = file_get_contents('https://www.example.com/image.jpg');
if ($file === false) { // do stuff on failure }

It works flawlessly but the thing is that today I just realized that some files have been deleted or something but still the response code is 200 so file_get_contents() returns empty string which means "" === false // is false so it won't execute that code in that if condition.

My question is how to properly write that if condition to also check for an empty file?

My suggestions are:

if ($file == false) { // do stuff on failure or empty }

if ($file === false || strlen($file) === 0) { // do stuff on failure or empty }

if ($file === false || empty($file) { // do stuff on failure or empty }

PS For now I am only interested in suggestions for file_get_contents()

  • If it returns an empty string if the file doesn't exist, then it should be enough to do what you wrote, check if it's falsy: `if (!$file)` or `if ($file == false)`. You already seem to know this so I'm not really sure what your question is? _Side note:_ Checking both false and empty isn't necessary since false also is regarded as empty. – M. Eriksson Aug 29 '21 at 01:32
  • Yes, you are right `empty()` is not needed, if I use double equals but I asked for suggestions because of potential false positives. My third example was with triple equals, that's why I put `empty()` but probably my first example is enough or yours with `if(!$file)`. Edit: yes i see, thank you :) –  Aug 29 '21 at 03:16
  • _"Yes, you are right empty() is not needed, if I use double equals"_ - True, but my point was that the `$file === false` is not needed if you use `empty()` since `empty()` will return true if the value literally is `false` as well. – M. Eriksson Aug 29 '21 at 10:25
  • Yes sure I understand. I can use only `if( empty($file) )` because this becomes true both with empty string or false –  Aug 29 '21 at 20:40

0 Answers0