我有一个表单,除了文件上传,我保持对其他输入类型的验证,但如果我不选择任何文件,那么我的脚本是在上传表中添加一个空的。有没有办法检查用户是否正在上传任何文件,如果有文件,那么我可以运行我的上传脚本......这是脚本
if (isset($_FILES['fileupload'])) {
$errors = array();
$connection = db::factory('mysql');
$user_id = $_SESSION['userid'];
foreach ($_FILES['fileupload']['tmp_name'] as $key => $tmp_name) {
$file_name = $_FILES['fileupload']['name'][$key];
$file_size = $_FILES['fileupload']['size'][$key];
$file_tmp = $_FILES['fileupload']['tmp_name'][$key];
$file_type = $_FILES['fileupload']['type'][$key];
if ($file_size > 2097152) {
$errors[] = 'File size must be less than 2 MB';
}
$upload_dir = ROOT;
$desired_dir = ROOT . "/uploads/";
if (empty($errors) == true) {
if (is_dir(ROOT . "/uploads/") == false) {
mkdir(ROOT . "/uploads/", 0700);
}
if (is_dir(ROOT . "/uploads/" . $file_name) == false && !file_exists(ROOT . "/uploads/" . $file_name)) {
$file_path = ROOT . "/uploads/" . $file_name;
move_uploaded_file($file_tmp, $file_path);
$full_path = mysql_real_escape_string($file_path);
$query = "INSERT INTO uploads (`User_Id`,`File_Name`,`File_Path`,`File_Size`,`File_Type`) VALUES('$user_id','$file_name','$full_path','$file_size','$file_type'); ";
mysql_query($query);
} else {
$new_path = ROOT . "/uploads/" . time() . "_" . $file_name;
rename($file_tmp, $new_path);
$file_path = $new_path;
$full_path = mysql_real_escape_string($file_path);
$query = "INSERT INTO uploads (`User_Id`,`File_Name`,`File_Path`,`File_Size`,`File_Type`) VALUES('$user_id','$file_name','$full_path','$file_size','$file_type'); ";
mysql_query($query);
}
} else {
print_r($errors);
}
}
if (empty($error)) {
//echo "Success"; exit;
return true;
}
return false;
答案 0 :(得分:1)
如果我没记错的话,文件上传字段将在$ _FILES中创建一个条目,无论它是否为空。在这种情况下,您最好检查$_FILES['fileupload']['size'][$key]
是否大于零或$_FILES['fileupload']['name'][$key]
不为空。
这应该可以为您在表单上的每个文件上传提供答案(即使您有很多文件)。
答案 1 :(得分:0)
在foreach loop
内,
把条件
if($_FILES['fileupload']['name'][$key]!="")
{
//your code
}