多个文件在​​多维数组上载 [英] Multiple files uploading in multidimensional array

查看:140
本文介绍了多个文件在​​多维数组上载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有数目不详的行,其中用户可以上传文件的PHP形式。为这个目的,我使用二维阵列。

 <形式的行动=upload_file_module.php方法=POSTENCTYPE =的multipart / form-data的>
&LT ;? $ I = 0; ?>
<表>
    &所述; TR>
        &所述; TD>
            <输入类型=隐藏名称=行[&LT ;?回声$ I;?>] [ROW_NAME]VALUE =一/>一
        < / TD>
        &所述; TD>
            <输入类型=文件名称=行[&LT ;?回声$ I;?>] [fileToUpload]>
        < / TD>
        &LT ;?
            $ I ++;
        ?>
    < / TR>    &所述; TR>
        &所述; TD>
            <输入类型=隐藏名称=行[&LT ;?回声$ I;?>] [ROW_NAME]VALUE =两化/>二
        < / TD>
        &所述; TD>
            <输入类型=文件名称=行[&LT ;?回声$ I;?>] [fileToUpload]>
        < / TD>
        &LT ;?
            $ I ++;
        ?>
    < / TR>
< /表><输入类型=提交值=上传NAME =提交>

所有文件应保存在不同的文件夹。

 < PHP
$ UNIQUE_ID =文件夹;
$ UNIQUE_ID = $ UNIQUE_ID。 '/';
的foreach($ _ POST ['行']为$ VAL){    $ TARGET_DIR = $ UNIQUE_ID;
    $ TARGET_DIR = $ TARGET_DIR。 /。 $ VAL。 /;
    如果(!file_exists($ TARGET_DIR)){
        的mkdir($ TARGET_DIR,0777,真正的);
    }    呼应'<表>';
    呼应'< TR>';
    呼应'< TD>',$ VAL ['ROW_NAME'],'< / TD>';
    呼应'< TD>',$ VAL ['fileToUpload'],'< / TD>';
    呼应'< / TR>';
    呼应'< /表>';    $ TARGET_FILE = $ TARGET_DIR。基本名($ _ FILES [$ VAL ['fileToUpload] [名称]);
    $ uploadOk = 1;
    $ imageFileType = PATHINFO($ TARGET_FILE,PATHINFO_EXTENSION);
    //检查映像文件是一个实际的图像或图像假货    //检查文件已经存在
    如果(file_exists($ TARGET_FILE)){
        回声对不起,文件已经存在。
        $ uploadOk = 0;
    }
    //检查文件大小
    如果($ _FILES [fileToUpload] [大小> 9亿){
        回声对不起,您的文件过大。
        $ uploadOk = 0;
    }    //检查$ uploadOk被错误设置为0
    如果($ uploadOk == 0){
        回声对不起,您的文件没有上传。
    //如果一切正常,尝试上传文件
    }其他{
        如果(move_uploaded_file($ _ FILES [fileToUpload] [tmp_name的值],$ TARGET_FILE)){
            回声文件。基本名($ _FILES [fileToUpload] [名称])。 已上传< BR>中;
        }其他{
            回声抱歉,上传您的文件中的错误< BR>中;
        }
    }
}

但事实上它并没有看到任何文件,并输出结果如下:

有一个

对不起,文件已经exists.Sorry,你的文件没有上传。

两个

对不起,文件已经exists.Sorry,你的文件没有上传。


解决方案

有来进行,除了在评论的那些一些变化。主要问题是:


  1. 您正在尝试文件和post数据进入一个单一的阵列,当两个 $ _ POST $ _ FILES 是,在PHP性质,完全分开的实体。所以你结束了试图访问一个单一阵列时,有实际上是两个这两个超全局变量数组里面

  2. $ TARGET_FILE 从未宣称,你的 $ TARGET_DIR 有太多的斜杠。

  3. 项的 1 让你访问 $ VAL 走错了路。

这是最后的修正,我想出了,保持逻辑为自己的环境。每个声部的解释是注释的code内。

HTML表单

\r
\r

<!DOCTYPE HTML>\r
< HTML和GT;\r
< HEAD>< /头>\r
<身体GT;\r
<形式的行动=upload.php的方法=POSTENCTYPE =的multipart / form-data的>\r
            <表>\r
< PHP $反= 2; //待打印要字段数\r
为($ I = 0; $ I< $计数器; $ I ++)//做正确的计数>\r
                &所述; TR>\r
&所述; TD>\r
<输入类型=隐藏名称=行[]VALUE =< PHP的echo $ I;?>/>文件:\r
< / TD>\r
&所述; TD>\r
<输入类型=文件名称=行[]>\r
< / TD>\r
< / TR>\r
< PHP ENDFOR; ?>\r
< /表>\r
<输入类型=提交值=上传NAME =提交>\r
< /表及GT;\r
< /身体GT;\r
< / HTML>

\r

\r
\r

PHP脚本后

 < PHP
    $ UNIQUE_ID =上载; //只是改变重现
    $ UNIQUE_ID = $ UNIQUE_ID。 '/';
    的foreach($ _ POST ['行']为$ VAL){        $ TARGET_DIR = $ UNIQUE_ID;
        $ TARGET_FILE = $ _FILES ['行'] ['名'] [$ VAL]; //实际上定义这个变种
        $ TARGET_DIR = $ TARGET_DIR。 $ VAL。 /; //无需索引assoc命令也不是'/'
        如果(!file_exists($ TARGET_DIR)){
            的mkdir($ TARGET_DIR,0777,真正的);
        }        $ imageFileType = PATHINFO($ TARGET_DIR,PATHINFO_EXTENSION);
        //检查映像文件是一个实际的图像或图像假货        //检查文件已经存在
        如果(file_exists($ TARGET_FILE)){
            死(对不起,文件已经存在。); //死,如果错误
        }
        //检查文件大小
        如果($ _FILES ['行'] ['大小'] [$ VAL]≥9亿){使用文件的正确索引引用//
            死(对不起,您的文件过大。); //死,如果错误
        }        //检查是否有$ _FILES错误味精
        如果($ _FILES ['行'] ['错误'] [$ VAL]!= 0){
            死(对不起,你的文件没有上传。); //死,如果错误
            //如果一切正常,尝试上传文件
        }其他{
            //与实际文件的最终点名称move_files被感动
            如果(move_uploaded_file($ _ FILES ['行'] ['tmp_name的值'] [$ VAL],$ TARGET_DIR。'/'。$ _ FILES ['行'] ['名'] [$ VAL)){
                回声文件。基本名($ _ FILES ['行'] ['名'] [$ VAL])。 已上传< BR>中;
            }其他{
                死(抱歉,上传您的文件中的错误。);
            }
        }
    }

最终输出(上传后两个虚拟的文件)

 阵列

    [行] =>排列
        (
            [0] => 0
            [1] => 1
        )    [提交] =>上传

排列

    [行] =>排列
        (
            [名] =>排列
                (
                    [0] => dummyfile1.docx
                    [1] => dummyfile2.mpp
                )            [类型] = GT;排列
                (
                    [0] =>应用程序/ vnd.openxmlformats-officedocument.wordpro​​cessingml.document
                    [1] =>应用程序/ vnd.ms项目
                )            [tmp_name的值] =>排列
                (
                    [0] => C:\\ WINDOWS \\ TEMP \\ php73DA.tmp
                    [1] => C:\\ WINDOWS \\ TEMP \\ php73DB.tmp
                )            [错误] =>排列
                (
                    [0] => 0
                    [1] => 0
                )            [大小] = GT;排列
                (
                    [0] => 0
                    [1] => 180224
                )        ))
文件dummyfile1.docx已上传。
文件dummyfile2.mpp已上传。

I have a php form with unknown number of rows where user can upload files. For this purpose I use two dimensional array.

<form action="upload_file_module.php" method="post" enctype="multipart/form-data">
<? $i = 0; ?>
<table>
    <tr>
        <td>
            <input type="hidden" name="row[<? echo $i; ?>][row_name]" value = "one"/> One
        </td>
        <td>
            <input type="file" name="row[<? echo $i; ?>][fileToUpload]" >
        </td>
        <? 
            $i++;
        ?>
    </tr>

    <tr>
        <td>
            <input type="hidden" name="row[<? echo $i; ?>][row_name]" value = "two"/> Two
        </td>
        <td>
            <input type="file" name="row[<? echo $i; ?>][fileToUpload]" >
        </td>
        <? 
            $i++;
        ?>
    </tr>
</table>    

<input type="submit" value="Upload" name="submit">

All files should be saved in different folders.

<?php
$unique_id = "folder";
$unique_id = $unique_id . '/';
foreach ( $_POST['row'] as $val )   {

    $target_dir = $unique_id;
    $target_dir = $target_dir . "/" . $val. "/";
    if (!file_exists($target_dir)) {
        mkdir($target_dir, 0777, true);
    }

    echo '<table>';
    echo '<tr>';
    echo '<td>', $val['row_name'], '</td>';
    echo '<td>', $val['fileToUpload'], '</td>';
    echo '</tr>';
    echo '</table>';

    $target_file = $target_dir . basename($_FILES[$val['fileToUpload']]["name"]);
    $uploadOk = 1;
    $imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
    // Check if image file is a actual image or fake image

    // Check if file already exists
    if (file_exists($target_file)) {
        echo "Sorry, file already exists.";
        $uploadOk = 0;
    }
    // Check file size
    if ($_FILES["fileToUpload"]["size"] > 900000000) {
        echo "Sorry, your file is too large.";
        $uploadOk = 0;
    }

    // Check if $uploadOk is set to 0 by an error
    if ($uploadOk == 0) {
        echo "Sorry, your file was not uploaded.";
    // if everything is ok, try to upload file
    } else {
        if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
            echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.<br>";
        } else {
            echo "Sorry, there was an error uploading your file.<br>";
        }
    }      
}

But in fact it doesn't see any files, and output looks like:

one

Sorry, file already exists.Sorry, your file was not uploaded.

two

Sorry, file already exists.Sorry, your file was not uploaded.

解决方案

There were some changes to be made, in addition to the ones in the comments. Major issues are:

  1. You were trying to get both files and post data into one single array, when both $_POST and $_FILES are, in PHP nature, totally separated entities. So you're ending up trying to access a single array row when there is actually two row arrays inside both these superglobals.
  2. Your $target_file was never declared, and your $target_dir has too many slashes.
  3. The item 1 made you access $val the wrong way.

These are the final corrections I came up with, keeping the logic for your own environment. The explanation to each part is commented inside the code.

HTML form

<!DOCTYPE html>
<html>
<head></head>
<body>
	<form action="upload.php" method="post" enctype="multipart/form-data">
            <table>
	<?php $counter = 2; // number of fields you want to be printed
	for($i = 0; $i < $counter; $i++): // do proper counting ?>
                <tr>
			<td>
				<input type="hidden" name="row[]" value="<?php echo $i; ?>"/> File:
			</td>
			<td>
				<input type="file" name="row[]" >
			</td>
		</tr>
	<?php endfor; ?>
	    </table>
	    <input type="submit" value="Upload" name="submit">
	</form>
</body>
</html>

PHP Post Script

<?php
    $unique_id = "upload"; // just changed to reproduce
    $unique_id = $unique_id . '/';
    foreach ($_POST['row'] as $val)   {

        $target_dir = $unique_id;
        $target_file = $_FILES['row']['name'][$val]; //actually defining this var
        $target_dir = $target_dir . $val. "/"; // no need to index assoc nor '/'
        if (!file_exists($target_dir)) {
            mkdir($target_dir, 0777, true);
        }

        $imageFileType = pathinfo($target_dir,PATHINFO_EXTENSION);
        // Check if image file is a actual image or fake image

        // Check if file already exists
        if (file_exists($target_file)) {
            die("Sorry, file already exists."); // die if error
        }
        // Check file size
        if ($_FILES['row']['size'][$val] > 900000000) { // using the proper index reference for file
            die("Sorry, your file is too large."); //die if error
        }

        // Check if there are error msg in $_FILES
        if ($_FILES['row']['error'][$val] != 0) {
            die("Sorry, your file was not uploaded."); // die if error
            // if everything is ok, try to upload file
        } else {
            // point your move_files with the final name of the actual file to be moved
            if (move_uploaded_file($_FILES['row']['tmp_name'][$val], $target_dir.'/'.$_FILES['row']['name'][$val])) {
                echo "The file ". basename($_FILES['row']['name'][$val]). " has been uploaded.<br>";
            } else {
                die("Sorry, there was an error uploading your file.");
            }
        }
    }

Final Output (after uploading two dummy files)

Array
(
    [row] => Array
        (
            [0] => 0
            [1] => 1
        )

    [submit] => Upload
)
Array
(
    [row] => Array
        (
            [name] => Array
                (
                    [0] => dummyfile1.docx
                    [1] => dummyfile2.mpp
                )

            [type] => Array
                (
                    [0] => application/vnd.openxmlformats-officedocument.wordprocessingml.document
                    [1] => application/vnd.ms-project
                )

            [tmp_name] => Array
                (
                    [0] => C:\Windows\Temp\php73DA.tmp
                    [1] => C:\Windows\Temp\php73DB.tmp
                )

            [error] => Array
                (
                    [0] => 0
                    [1] => 0
                )

            [size] => Array
                (
                    [0] => 0
                    [1] => 180224
                )

        )

)
The file dummyfile1.docx has been uploaded.
The file dummyfile2.mpp has been uploaded.

这篇关于多个文件在​​多维数组上载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆