0

我有一个表单,除了文件上传,我保留了对其他输入类型的验证,但是如果我不选择任何文件,那么我的脚本会在上传表中添加一个空。有没有办法检查用户是否正在上传任何文件和如果有文件,那么我可以运行我的上传脚本......这是脚本

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;
4

2 回答 2

1

如果我没记错的话,文件上传字段将在 $_FILES 中创建一个条目,无论它是否为空。在这种情况下,您最好检查$_FILES['fileupload']['size'][$key]是否大于零或$_FILES['fileupload']['name'][$key]不为空。

这应该为您在表单上上传的每个文件提供答案(即使您有很多。)

于 2013-08-02T10:51:01.860 回答
0

在你的里面foreach loop
把条件

if($_FILES['fileupload']['name'][$key]!="")
{
  //your code
}
于 2013-08-02T11:04:40.727 回答