Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

error clause for file_put_contents

I am using this line to obtain and save an image from a URL.

file_put_contents("./images/".$pk.".jpg", file_get_contents($PIC_URL))

I am unsure what the best way to deal with an error is. At the moment it is failing because there is no permission, which will be remedied shortly, but I would like it to be able to deal with situations where PIC_URL is empty or not an image. Should I dead with the error at this level(probably it is better for permission related things) or should I check higher up if PIC_URL is empty, or both?

Which is the best approach?

like image 732
Joshxtothe4 Avatar asked Feb 06 '09 11:02

Joshxtothe4


2 Answers

I would use is_writable(), passing it the folder name if the image doesn't already exist, or the filename if it does, before you attempt to write the image.

http://uk3.php.net/manual/en/function.is-writable.php

like image 117
benlumley Avatar answered Oct 12 '22 23:10

benlumley


I'm not talented enough to claim this is the best method, but I would just test along the way:

$imageDir = "/path/to/images/dir/";
$imagePath = "$imageDir$pk.jpg";
if (!is_dir($imageDir) or !is_writable($imageDir)) {
    // Error if directory doesn't exist or isn't writable.
} elseif (is_file($imagePath) and !is_writable($imagePath)) {
    // Error if the file exists and isn't writable.
}

$image = file_get_contents(urlencode($PIC_URL));
if (empty($image)) {
    // Error if the image is empty/not accessible.
    exit;
}

file_put_contents($imagePath, $image);
like image 30
chuckg Avatar answered Oct 13 '22 00:10

chuckg