如何上传带有用户名,密码,多个文件上传的HTML表单,然后使用PHP处理它?

时间:2020-03-06 14:45:55  来源:igfitidea点击:

如何从单个html表单发布用户名,密码和多个二进制文件并使用php处理它?我不允许使用ajax。

解决方案

我们应该使用$ _FILESsuperglobal和move_uploaded_file()函数查看哪些文件已成功上传,并将它们移至最终位置(以防万一)。

$ _POST`超级全局将包含提交的用户名和密码。

首先,请查看PHP.net上的这些页面

  • 文件上传信息
  • move_uploaded_file

但是,为了让我们入门,这里有几个存根文件。

uploadForm.html

<html>
<body>
    <form action="processStuff.php" enctype="multipart/form-data" method="POST">
        username: <input type="text" name="username" />
        password: <input type="password" name="password" />

        <p>
            <input type="file" name="uploadFile[]" /><br />
            <input type="file" name="uploadFile[]" /><br />
            <input type="file" name="uploadFile[]" /><br />
            <!-- Add as many of these as you want -->
        </p>

        <p>
            <input type="submit" />
        </p>
    </form>
</body>
</html>

processStuff.php

<pre>
<?php

    echo '<h2>Username & password</h2>'
    echo "Username: {$_POST['username']}\nPassword: {$_POST['password']}";
    echo '<hr />';

    echo '<h2>Uploaded files</h2>'  
    foreach($_FILES['uploadFile']['tmp_name'] as $i => $tempUploadPath) {
        if (empty($tempUploadPath)) {
            // this <input type="file" /> was "blank"... no file selected
        } else {
            // a file was uploaded
            echo '<strong>A file named "', $_FILES['uploadFile']['name'][$i], "\" was uploaded</strong>\n";
            echo "\ttemporarily stored at: ", $tempUploadPath, "\n";            
            echo "\tmime type: ", $_FILES['uploadFile']['type'][$i], "\n";
            echo "\tsize: ", $_FILES['uploadFile']['size'][$i], " bytes\n";         
            echo "\terror code", 
            ((empty($_FILES['uploadFile']['size'][$i]) 
                    ? '<em>no errror</em>' 
                    : $_FILES['uploadFile']['size'][$i])), 
            "\n\n";

    // do something useful with the uploaded file 
        // access it via $tempUploadPath and use move_uploaded_file() to move 
        //     it out of the temp path before you manipulate it in any way!!!!!
        // see http://us3.php.net/features.file-upload
        // and http://us3.php.net/manual/en/function.move-uploaded-file.php
        }       
    }

?>
</pre>

HTML文件显示了如何设置<form>的enctype,第二个表单显示了如何访问提交的用户名和密码,以及最后如何循环访问每个上载的文件。

如前所述,我们必须尽快移动文件。它们已上传到临时位置,除非我们处理它们,否则系统将删除它们。因此,请先将它们移到某个地方,然后再执行我们需要的操作。

帮忙这有帮助

阿林