W D
W D

Reputation: 115

Upload Multiple Files HTML5 / PHP

I'm trying to build a basic upload form to add multiple files to a folder, which is processed by PHP.

The HTML code I have is:

<form id="form" action="add-files-php.php" method="POST" enctype="multipart/form-data">
    <div class="addSection">Files To Add:<br><input type="file" name="files[]" multiple /></div>
    <div class="addSection"><input type="submit" name="submit" value="Add Files" /></div>
</form>

And the PHP to process is:

$file_path = "../a/files/article-files/$year/$month/";
foreach ($_FILES['files']['files'] as $file) {    
    move_uploaded_file($_FILES["file"]["name"],"$file_path");
}

I can run the PHP without any errors, but the files don't get added to the path folder.

Where am I going wrong with this?

Upvotes: 2

Views: 3170

Answers (2)

Ruslan Osmanov
Ruslan Osmanov

Reputation: 21502

Iterate the $_FILES['files']['error'] array and check if the files are actually uploaded to the server:

$dest_dir = "../a/files/article-files/$year/$month";
foreach ($_FILES["files"]["error"] as $key => $error) {
  if ($error == UPLOAD_ERR_OK) {
    // The temporary filename of the file stored on the server
    $tmp_name = $_FILES["files"]["tmp_name"][$key];
    $name = basename($_FILES["files"]["name"][$key]);
    // Handle possible failure of the move_uploaded_file() function, too!
    if (! move_uploaded_file($tmp_name, "$dest_dir/$name")) {
      trigger_error("Failed to move $tmp_name to $dest_dir/$name",
        E_USER_WARNING);
    }
  } else {
    // Handle upload error
    trigger_error("Upload failed, key: $key, error: $error",
      E_USER_WARNING);
  }
}

The biggest issue with your code is that you are trying to move $_FILES['files']['name'] instead of $_FILES['files']['tmp_name']. The latter is a file name of temporary file uploaded into the temporary directory used for storing files when doing file upload.

P.S.

Using relative paths is error-prone. Consider using absolute paths with the help of a constant containing path to the project root, e.g.:

config.php

<?php
define('MY_PROJECT_ROOT', __DIR__);

upload.php

<?php
require_once '../some/path/to/project/root/config.php';

$dest_dir = MY_PROJECT_ROOT . "/a/files/article-files/$year/$month";

Upvotes: 1

user2506641
user2506641

Reputation:

I have a similar code actually in one of my projects. Try it.

foreach ($_FILES['files']['name'] as $f => $name) {
    move_uploaded_file($_FILES["files"]["tmp_name"][$f], $file_path);
}

Look at the following page: http://php.net/manual/en/function.move-uploaded-file.php

EDIT: Nowhere in the code you provided, does it show that you actually give your file a filename, you simply refer to a path, rather than a path+filename+extension

move_uploaded_file($_FILES["files"]["tmp_name"][$f], $file_path . $name);

modifying my original code sample to be like the second one, should work.

Upvotes: 2

Related Questions