Jos*_*he4 8 php error-handling
我正在使用此行来获取并保存URL中的图像.
file_put_contents("./images/".$pk.".jpg", file_get_contents($PIC_URL))
Run Code Online (Sandbox Code Playgroud)
我不确定处理错误的最佳方法是什么.目前它失败了,因为没有许可,很快就会得到补救,但我希望它能够处理PIC_URL为空或不是图像的情况.我应该死在这个级别的错误(可能是与权限相关的事情更好)或者我应该检查更高的PIC_URL是空的,还是两者都检查?
哪种方法最好?
chu*_*ckg 11
我没有足够的天赋来宣称这是最好的方法,但我会沿途测试:
$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);
Run Code Online (Sandbox Code Playgroud)