I’m trying to upload two files with one form post however my form will only upload the first file and doesn’t iterate over the 2nd file and upload. Any idea why? The code I’m using is below.
<?php
$upload = $_POST['upload'];
$enteredPassword = $_POST['password'];
$uploadedFiles = $_FILES;
$password = "************";
// Where the file is going to be placed
$target_path = "";
//interger count
$i = 0;
//upload the files
if ($upload == true && $enteredPassword == $password) {
foreach($uploadedFiles as $uploadedFile) {
$target_path = $target_path . $uploadedFile['name'][$i];
if(move_uploaded_file($uploadedFile['tmp_name'][$i], $target_path)) {
echo "<p>The file ". $uploadedFile['name'][$i].
" has been uploaded.</p>";
} else{
echo "<p>There was an error uploading the {$uploadedfile['name']}, please try again!</p>";
}
$i++;
}
}
?>
<ul>
<form enctype="multipart/form-data" action="" method="post">
<input type="hidden" name="upload" value="true" />
<li>Choose a file to upload:</li>
<li><input name="userfile[]" type="file" size="40" /></li>
<li><input name="userfile[]" type="file" size="40" /></li>
<li>Enter password for file upload:</li>
<li><input name="password" type="password" size="40" /></li>
<li><input type="submit" value="Upload File" /></li>
</form>
</ul>
The behavior is expected because there is only one element in your $_FILES array which is $_FILES[“userfile”]. You can try something like this to achieve what you want: