我已经阅读了其他主题,但我无法将其他答案应用到我的代码中:S
我有这个函数
function add_image($cFile) {
//SET SETTINGS FOR THE IMAGE
$target_dir = "../images/cuisines/";
$target_file = $target_dir . basename($_FILES["cImage"]["name"]);
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
$cFile = basename($_FILES["cImage"]["name"], '.'. $imageFileType).uniqid($prefix = '-', $more_entropy = null) .'.'. $imageFileType;
//BUT FIRST CHECK IF THERE IS NOT FILE
if ($_FILES['cImage']['size'] == 0) {
echo "<script>alert('You forgot the image, you must complete the form again');</script>" ;
echo '<script>window.location="'. $_SERVER['HTTP_REFERER'] .'"</script>' ;
exit();
}
// CHECK IF THE FILE IS AN IMAGE
$check = getimagesize($_FILES["cImage"]["tmp_name"]);
if($check == false) {
echo "<script>alert('This is not an Image, you must complete the form again');</script>" ;
echo '<script>window.location="'. $_SERVER['HTTP_REFERER'] .'"</script>' ;
exit();
}
//ALLOW CERTAIN KIND OF FILES
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
echo "<script>alert('Sorry, only JPG, JPEG, PNG & GIF files are allowed, you must complete the form again');</script>" ;
echo '<script>window.location="'. $_SERVER['HTTP_REFERER'] .'"</script>' ;
exit();
}
if(move_uploaded_file($_FILES["cImage"]["tmp_name"], $target_dir.$cFile)) {
return $cFile;
} else {
return false;
}
}
然后如果函数成功,我想这样做:
if (add_image($cFile) !== false) {
echo $cfile;
}
谁能帮我知道我做错了什么?我读过类似的主题,但我不能在我的情况下使用它们。
我收到的错误是关于变量cFile在代码的第二部分不存在:S
如果函数失败,它看起来会终止整个脚本,所以您可以访问底部代码的唯一方法是如果函数成功。
您可能不需要if
语句。
如果函数失败,可能更好的方法是检查return false;
,然后检查if (add_image($cFile) !== false)
可能是$target_dir,可能没有写访问权限。如果没有,使用chmod命令为target_dir添加写权限