Reputation: 25
I am trying different examples of PHP multiple file upload like this one
<html>
<body>
<form action="upload.php" enctype="multipart/form-data" method="post">
<div>
<label for='upload'>Add files</label>
<input id='upload' name="upload[]" type="file" multiple="multiple" />
</div>
<p><input type="submit" name="submit" value="Submit"></p>
</form>
</body>
</html>
<?php
if(isset($_POST['submit'])){
if(count($_FILES['upload']['name']) > 0){
//Loop through each file
for($i=0; $i<count($_FILES['upload']['name']); $i++) {
//Get the temp file path
$tmpFilePath = $_FILES['upload']['tmp_name'][$i];
//Make sure we have a filepath
if($tmpFilePath != ""){
//save the filename
$shortname = $_FILES['upload']['name'][$i];
//save the url and the file
$filePath = $_FILES['upload']['name'][$i];
//Upload the file into the temp dir
if(move_uploaded_file($tmpFilePath, $filePath)) {
$files[] = $shortname;
//insert into db
//use $shortname for the filename
//use $filePath for the relative url to the file
}
}
}
}
//show success message
echo "<h1>Uploaded:</h1>";
if(is_array($files)){
echo "<ul>";
foreach($files as $file){
echo "<li>$file</li>";
}
echo "</ul>";
}
}
?>
Problem is that it detects 3 files but uploads only 2 and the first one is always missing. I don't get any error message so can't understand what is going on. I've tried some other samples of multi upload code but situation is the same.
Upvotes: 0
Views: 46
Reputation: 16688
I read this comment:
https://www.php.net/manual/en/reserved.variables.files.php#89674
And the files are not number file0
, file1
, file2
, etc, but file1
, file2
, file3
. It could be that the numeric indexes are also not 0
, 1
, 2
, etc, but 1
, 2
, 3
, etc. So in your case you could correct for that by doing:
$tmpFilePath = $_FILES['upload']['tmp_name'][$i+1];
$shortname = $_FILES['upload']['name'][$i+1];
$filePath = $_FILES['upload']['name'][$i+1];
I haven't tested this, and I'm not at all sure about this, but it is easy for you to check it, just do a:
var_dump($_FILES);
Upvotes: 1