Reputation: 4193
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?
Upvotes: 15
Views: 51030
Reputation: 17
Hmm couldn't you also just do
file_put_contents($file, $str) or die("Unable to write file!");
Upvotes: 0
Reputation: 7956
try making a function for this.
<?php
define('OK', 0);
deinfe('URL_EMPTY', 1);
define('WRITING_PROBLEMS',2);
define('OTHER_PROBLEM', 3);
function save_pic($pic_url) {
$imageDir = '/path/to/images/dir/';
if (!strlen($pic_url))
return URL_EMPTY;
if (!is_dir($imageDir) || !is_writable($imageDir)) {
return WRITING_PROBLEMS;
}
$image = file_get_contents(urlencode($pic_url));
$pk = time(); // or whatever you want as key
$r = file_put_contents($imagePath.$pk.".jpg", $pic_url);
if ($r)
return OK;
else
return OTHER_PROBLEM;
}
?>
Upvotes: 2
Reputation: 9415
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);
Upvotes: 19
Reputation: 3678
Both, as far as I am concern. Especially with those dangerous file handling functions, double-checking doesn't hurt. (Where does $pk
come from?)
Generally, check higher up for nicer feedback to the user and check right before you execute for security. Its hard to give decent feedback to the user when only checking at a low level. On the other hand, it is hard to check for all possible errors (like those file system permissions) on a high and generic level.
Upvotes: 0
Reputation: 11382
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.
https://www.php.net/manual/en/function.is-writable.php
Upvotes: 3