如何使用PHP处理多个文件上传

如何使用PHP处理多个文件上传

本文介绍了如何使用PHP处理多个文件上传的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用 PHP 上传文件,但问题是我不知道要上传多少个文件.

I want to upload files using PHP but the problem is that I don't know how many files I will upload.

我的问题是,如果我使用file[],我该如何上传文件?

My question is how can I upload files if I use file[]?

<form action="upload.php" method="post" enctype="multipart/form-data">
<label for="file">Filename:</label><input type="file" name="file[]" id="file" />
<br />
<label for="file">Filename:</label><input type="file" name="file[]" id="file" />
<br />
<input type="submit" name="submit" value="Submit" />
</form>

我将只添加文件框,我将使用 JavaScript 创建更多要上传的文件输入,但如何在 PHP 中处理它们?

I will add just File box and I will use JavaScript to create more file input to upload but how to handle them in PHP?

推荐答案

参见:$_FILES, 处理文件上传

<?php
    if(isset($_FILES['file']['tmp_name']))
    {
        // Number of uploaded files
        $num_files = count($_FILES['file']['tmp_name']);

        /** loop through the array of files ***/
        for($i=0; $i < $num_files;$i++)
        {
            // check if there is a file in the array
            if(!is_uploaded_file($_FILES['file']['tmp_name'][$i]))
            {
                $messages[] = 'No file uploaded';
            }
            else
            {
                // copy the file to the specified dir
                if(@copy($_FILES['file']['tmp_name'][$i],$upload_dir.'/'.$_FILES['file']['name'][$i]))
                {
                    /*** give praise and thanks to the php gods ***/
                    $messages[] = $_FILES['file']['name'][$i].' uploaded';
                }
                else
                {
                    /*** an error message ***/
                    $messages[] = 'Uploading '.$_FILES['file']['name'][$i].' Failed';
                }
            }
        }
    }
?>

这篇关于如何使用PHP处理多个文件上传的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-30 22:20