同时将文件上传到同一目录

时间:2014-02-21 16:58:36

标签: php file-upload

对于我的部分网络应用,我正在尝试以2个不同的名称上传1个文件。第一个名称是用户指定的原始文件名。这将在我的应用程序中稍后用于参考。第二个名称是一个更改的名称(只需添加一个计数器变量)。要使用move_uploaded_file($ name,$ path)上传单个文件,它就像魅力一样。当我尝试在另一个之后调用一个move_uploaded_file(...)时,只有第一个函数会上传文件。第二个函数不会返回错误消息。

在线查看后,似乎可以通过循环完成。我将名称和路径放在一个数组中,使用foreach循环遍历它,但只上传了第一个文件。

以下是文件及其相关部分,因为有些文件是冗长的。

mainPage.php在我的所有页面上应用标题。 verifyFile.php是执行上载以及验证批量处理以检查文件是否有效的文件。

workPage.php

<?php
session_start();
require("mainPage.php");

?> 
<link rel = "stylesheet" type = "text/css" href = "CSS/workpageCSS.css" />
<div id = "pageContainer">
    <form enctype = "multipart/form-data" action = "verifyFile.php" method = "post">
        <table border = "0" cellpadding = "2" cellspacing = "5">
            <tr>
                <td>
                    <label for = "fileName">Select file to upload</label>
                </td>
                <td>
                    <input type = "file" name = "file" id = "fileName" placeholder = "Choose file path" autofocus = "autofocus" required = "required" />
                </td>
            </tr>
            <tr>
                <td></td>
                <td><input type = "submit" value = "Load file" /></td>
            </tr>
        </table>
    </form>
</div>

上传文件的verifyFile.php部分。

尝试1:

<?php 
session_start();
error_reporting(E_ALL);
ini_set('display_errors', '1');
    $dupFile = appendFileName(basename($_FILES['file']['name']));
$origToUpload = basename($_FILES['file']['name']);

$targetPath = ("uploads/".$dupFile);
$origTargetPath = "uploads/".$origToUpload;
if(move_uploaded_file($_FILES['file']['tmp_name'], $targetPath)) {
    #echo("Successfully uploaded ".basename($_FILES['file']['name']));
} else {
    echo("Failed 1<br />");
}

/*move_uploaded_file($_FILES['file']['tmp_name'], $origTargetPath); Does not upload but no errors are generated */
?>

尝试2

<?php
session_start();
error_reporting(E_ALL);
ini_set('display_errors', '1')
$filesToUpload = array($targetPath, $origTargetPath);

foreach($filesToUpload as $toUpload) {
    if(move_uploaded_file($_FILES['file']['tmp_name'], $toUpload)) {
        echo("worked!"); /* first time is successful and $targetPath is loaded onto my server */
    } else {
        echo("neg"); /* nothing is uploaded and returns neg */
    }
}
?>

$ origTargetPath和$ targetPath都是有效的,因为如果我在数组中反转它们,只会正确上传第一个文件。

有关其他信息,我正在通过XAMPP使用Apache。

1 个答案:

答案 0 :(得分:0)

当您致电move_upload_file时,php会将文件从文件临时位置移动到您指定的位置。所以你不能移动两次文件。

您正在寻找的是copy功能。在你的情况下(第一次尝试):

copy($targetPath, $origTargetPath);

您还可以考虑symlink