how can I prevent file_get_contents from creating an empty file when being used as a test condition in an if clause?
An empty file is created regardless, which causes a subsequent call in a different method to getimagesize() to fail.
The problem is, that as I have my code setup, the first time it is called will determine to save an image or to display a previously saved imaged. This is in part dependent on the presence of a file. As an empty file is created, this causes problems when calling my code subsequent times.
Is the easiest way to add a check if the file exists and is greater than 0?
Regardless of if my code works, file_get_contents will still output an error. This error is accounted for and dealt with(by my if condition), so I would like to avoid the error interrupting the output of my application if possible. Is there a way to turn this off without hiding actual errors?
if (file_put_contents($imageDir . $pk . '.jpg', file_get_contents($pic_url)))
{
return $imageDir . $pk . '.jpg';
}
else
{
return 'removed.jpg';
}
It isn't file_get_contents() that is creating an empty file, it is file_put_contents().
file_put_contents() will create a file even if the second parameter is empty. Hence, empty file.
You'll need to check the file exists first.
The easiest fix would be to move file_put_contents() inside the conditional, so that it only creates a file if there are contents.
if (($filecontents = file_get_contents($pic_url)) !== false)
{
file_put_contents($imageDir . $pk . '.jpg', $filecontents);
return $imageDir . $pk . '.jpg';
}
else
{
return 'removed.jpg';
}
Now, this still leaves you with a bunch of problems.
Check if the file exists using file_exists
:
if (file_exists($pic_url)) {
$contents = file_get_contents($pic_url);
if (!empty($contents)) {
file_put_contents($imageDir . $pk . '.jpg', $contents);
return $imageDir . $pk . '.jpg';
}
}
return 'removed.jpg';