我有一个图片上传表单,在上传文件之前我会调用多个函数,例如检查大小,尺寸以及它是否是有效图像。代码有效但调用函数并处理结果似乎非常麻烦和复杂。
是否有更简洁的方法来构建代码。
这就是我目前所拥有的:
if(checkvalidfile("img",$ext)){
if(checksize($size, 524288)) {
if(checkdimensions($tmp, 300)) {
$newfilename = renamefile($ext);
uploadfile($tmp, $bucket, "user_docs/agency_".$agency_id."/brand_logos/", $newfilename, $s3);
header('Location: ./message.php?action=newlogo');
} else {
echo "Your image can't be bigger than 300 x 300px";
die;
}
} else {
echo "File size is too big!";
die;
}
} else {
echo "Not a valid file";
die;
}
答案 0 :(得分:1)
由于您else
,因此无需die
。使用!
取消您的条件并将其全部取消:
if(!checkvalidfile("img",$ext)){
echo "Error message";
die;
}
if(!checksize($size, 524288)) {
echo "error message";
die;
}
if(!checkdimensions($tmp, 300)) {
echo "Error message";
die;
}
$newfilename = renamefile($ext);
uploadfile($tmp, $bucket, "user_docs/agency_".$agency_id."/brand_logos/", $newfilename, $s3);
header('Location: ./message.php?action=newlogo');
如果您认为die
不是正确的事情(绝对不是,这是一个非常糟糕的用户体验),那么您可以将您的条件放在一个函数中,该函数在失败时返回错误消息,或false
成功:
function checkValid() {
if(!checkvalidfile("img",$ext)
return "Error message 1";
if(!checksize($size, 524288))
return "error message 2";
if(!checkdimensions($tmp, 300))
return "error message 3";
return false;
}
if ($error = checkValid()) {
echo $error;
} else {
$newfilename = renamefile($ext);
uploadfile($tmp, $bucket, "user_docs/agency_".$agency_id."/brand_logos/", $newfilename, $s3);
header('Location: ./message.php?action=newlogo');
}