多文件上传 - 当所有文件上传失败时,只输入少量文件时工作正常

时间:2014-08-20 20:54:22

标签: php html mysql file-upload multiple-file-upload

我有这种形式,需要上传多个文件(最多10个文件)。这是html的样子:

<form action="fileupload.php" method="post" enctype="multipart/form-data">
<tr><td><input type="hidden" name="consultant_id" value="<?php echo $consult_id; ?>"></td></tr>

<tr><td>Offer letter:</td><td> Doc: <input type="file" name="myfile[]"></td></tr>
<tr><td>Project acceptance agreement:</td><td> Doc: <input type="file" name="myfile[]"></td></tr>
<tr><td>Employee book:</td><td> Doc: <input type="file" name="myfile[]"></td></tr>
<tr><td>W4 :</td><td> Doc: <input type="file" name="myfile[]"></td></tr>
<tr><td>State W4 :</td><td> Doc: <input type="file" name="myfile[]"></td></tr>
<tr><td><input type="submit" name="submit" value="Upload">  </td></tr>
</form></table>

我想将文件上传到服务器并将它们各自的路径存储在数据库(MySql)中。现在,当我输入所有文件字段(上传所有10个文件)时,下面的PHP代码工作得很棒,但是当我只想上传一些文件(比如5)时失败了。这是代码:

        <?php
    $consultant_id = $_POST['consultant_id'];
    echo $consultant_id;
    $verified_start_date = $_POST['verified_start_date'];

    // Assign valid types
    $valid_mime = array(
        'application/pdf',
        'image/jpeg',
        'image/jpg',



     );

    function upload($files, $dir, $size_limit=1024, $prevent_duplicate=false){
        global $valid_mime;

    // $files must be given.
    if(!isset($files)) return false;

    // Look for $valid_mime array.
    isset($valid_mime) and is_array($valid_mime) or die('Error in data resources, valid_mime array not found.');

    // Make directory if it does not exists. set permission to 0777.
    is_dir($dir) and chmod($dir, 0777) or mkdir($dir, 0777, true);
    //is_dir($consultant_id) and ($dir, 0777) or mkdir($dir/$consultant_id, 0777, true);
    $count = 1;
    foreach($files as $file){
        $file['error'] === UPLOAD_ERR_OK or die('Error in uploading file(s).');

        // Check uploaded-file type.
        in_array($file['type'], $valid_mime) or die();

        // Set size_limit in KB.
        $file['size'] > $size_limit*1024 and die('The uploaded file exceeds the maximum file size.');


        $file_extension = strrchr($file['name'], '.');
        $filename = basename($file['name'], $file_extension);

        $file_path = "{$dir}/{$filename}{$file_extension}";

        // Move uploaded-file from php temp folder to desire one.
        move_uploaded_file($file["tmp_name"], $file_path);

        // Make an array of filepaths
        $output[] = $file_path;
    }

    // Change permission of folder according to security issues.
    chmod($dir, 0755);

    return $output; 
}
/////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////  Controller Section  ////////////////////////////////

// Assign tmp_arr from $_FILES['myfile'] and do die if there is any problem.
$tmp_arr = (isset($_POST['submit']) and isset($_FILES['myfile'])) ? $_FILES['myfile'] : die('Error in posting data.');


// Create an array with desired structure.
for($i=0; $i<count($tmp_arr['name']); $i++){
    $files[] = array(
        'name'      =>  $tmp_arr['name'][$i],
        'type'      =>  $tmp_arr['type'][$i],
        'tmp_name'  =>  $tmp_arr['tmp_name'][$i],
        'error' =>  $tmp_arr['error'][$i],
        'size'      =>  $tmp_arr['size'][$i],
    );
}

// size_limit in KB
$path_arr = upload($files, './public/'.$consultant_id, 1024, true);
?>

我没有提到在数据库中输入数据的部分,因为我知道问题出现在$ tmp_arr [&#39;错误&#39;] [$ i]或$ file [&#39;错误&# 39;] === UPLOAD_ERR_OK或死亡(&#39;上传文件时出错。&#39;);

请看一下。

1 个答案:

答案 0 :(得分:0)

问题似乎是当您输入空白文件时,它会返回'error'值4,表示UPLOAD_ERR_NO_FILE。因此,由于该字段与UPLOAD_ERR_OK不匹配,您可以通过调用die在复制第一个空白后停止任何文件来立即停止所有代码。如果第一个字段为空白,则无法进入move_uploaded_file。如果十分之三为空白,则前两个文件将被复制,当第三个文件被处理时,它将停止任何进一步的文件。但是你仍然会在上传文件时看到错误&#34;错误。&#34;

编辑:

<?php
$consultant_id = $_POST['consultant_id'];
echo $consultant_id;
$verified_start_date = $_POST['verified_start_date'];

// Assign valid types
$valid_mime = array(
    'application/pdf',
    'image/jpeg',
    'image/jpg',



 );

function upload($files, $dir, $size_limit=1024, $prevent_duplicate=false){
    global $valid_mime;

    // $files must be given.
    if(!isset($files)) return false;

    //please use proper if statements. This is confusing.
    //isset($valid_mime) and is_array($valid_mime) or die('Error in data resources, valid_mime array not found.');

    // Look for $valid_mime array.
    if(!isset($valid_mime) || !is_array($valid_mime)) {
        die('Error in data resources, valid_mime array not found.');
    }

    //please use proper if statements. This is confusing.
    // is_dir($dir) and chmod($dir, 0777) or mkdir($dir, 0777, true);

    // Make directory if it does not exists. set permission to 0777.
    if(!is_dir($dir)) {
        mkdir($dir, 0777, true);
    } else {
        //try to chmod if the directory does exist
        chmod($dir, 0777);
    }

    if(!is_writable($dir)){
        die('Error unable to write to specified directory.');
    }

    foreach($files as $key=>$file){
        //switch case on the error code
        //you can find a list of these error codes at: http://php.net/manual/en/features.file-upload.errors.php
        switch($file['error']){
            default:
                //triggered if an unknown error happened. Newer php versions might bring new constants.
                //log error for this file
                $output[$key] = array('error'=>true, 'message'=>'An unknown error occurred');
                break;
            case UPLOAD_ERR_INI_SIZE:
                //log error for this file
                $output[$key] = array('error'=>true, 'message'=>'File size exceeds ini setting');
                break;
            case UPLOAD_ERR_FORM_SIZE:
                //log error for this file
                $output[$key] = array('error'=>true, 'message'=>'File size exceeds MAX_FILE_SIZE setting');
                break;
            case UPLOAD_ERR_PARTIAL:
                //log error for this file
                $output[$key] = array('error'=>true, 'message'=>'File was only partially uploaded');
                break;
            case UPLOAD_ERR_NO_FILE:
                //log error for this file
                $output[$key] = array('error'=>true, 'message'=>'File input was blank');
                break;
            case UPLOAD_ERR_NO_TMP_DIR:
                //log error for this file
                $output[$key] = array('error'=>true, 'message'=>'Missing temporary folder');
                break;
            case UPLOAD_ERR_CANT_WRITE:
                //log error for this file
                $output[$key] = array('error'=>true, 'message'=>'Failed to write file to disk');
                break;
            case UPLOAD_ERR_OK:
                //upload worked fine
                // Check uploaded-file type.
                if(in_array($file['type'], $valid_mime)){
                    // Set size_limit in KB.
                    if($file['size'] <= $size_limit*1024){
                        //get the file extension.
                        $file_extension = strrchr($file['name'], '.');
                        //get the filename
                        $filename = basename($file['name'], $file_extension);
                        //full filename and path
                        $file_path = "{$dir}/{$filename}{$file_extension}";

                        // Move uploaded-file from php temp folder to desire one.
                        // function returns true if the move was successful
                        if(move_uploaded_file($file["tmp_name"], $file_path)){
                            $output[$key] = array('error'=>false, 'message'=>'File was uploaded successfully', 'file'=>$file_path);
                        } else {
                            $output[$key] = array('error'=>true, 'message'=>'Unspecified error when moving the uploaded file');
                        }
                    } else {
                        //log error for this file
                        $output[$key] = array('error'=>true, 'message'=>'The uploaded file exceeds the maximum file size');
                    }
                } else {
                    //log error for this file
                    $output[$key] = array('error'=>true, 'message'=>'Failed to write file to disk');
                }
        }
    }

    // Change permission of folder according to security issues.
    chmod($dir, 0755);

    return $output; 
}

/////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////  Controller Section  ////////////////////////////////

// Assign tmp_arr from $_FILES['myfile'] and do die if there is any problem.
$tmp_arr = (isset($_POST['submit']) and isset($_FILES['myfile'])) ? $_FILES['myfile'] : die('Error in posting data.');


// Create an array with desired structure.
for($i=0; $i<count($tmp_arr['name']); $i++){
    $files[] = array(
        'name'      =>  $tmp_arr['name'][$i],
        'type'      =>  $tmp_arr['type'][$i],
        'tmp_name'  =>  $tmp_arr['tmp_name'][$i],
        'error' =>  $tmp_arr['error'][$i],
        'size'      =>  $tmp_arr['size'][$i],
    );
}

// size_limit in KB
$path_arr = upload($files, './public/'.$consultant_id, 1024, true);

如果我这样做,这就是我要使用的功能。如果一个上传的文件存在问题,则不会停止上传剩余文件,并将'error'密钥从$ _FILES转换为更友好的用户消息。您可以轻松地遍历返回数组并检查布尔值&#39;错误&#39;查看特定文件是否有问题的关键。如果&#39;错误&#39;是的,您可以回复消息供用户查看。如果没有错误,则消息&#39;文件已成功上传&#39;可以显示。返回数组中的键对应于传入的数组中的相同键。因此$ file [0]与$ returnResult [0]是相同的文件,以便于参考。