Excluding count($_FILES['files']['name'])
, you need to add [$i]
to each of your $_FILES
references, e.g., $_FILES['files']["tmp_name"][$i]
.
Also, $file["name"]
should be $_FILES['files']["name"][$i]
.
Question
I'm trying to allow for multiple image upload within a form. However it doesn't quite work and I can't spot the problem.
The form looks like this:
<form method="post" action="add-property.php" enctype="multipart/form-data">
<input type="file" multiple="multiple" name="files[]" />
<input type="submit" name="submit" class="property-submit" value="Submit Property" />
</form>
The PHP that follows (on the same page) is:
//Image logic
for ($i = 0; $i < count($_FILES['files']['name']); $i++) {
if (($_FILES['files']['type'] == "image/jpeg") || ($_FILES['files']['type'] == "image/png") || ($_FILES['files']['type'] == "image/jpg")) {
if ($_FILES['files']["error"] > 0) {
echo "Return Code: ".$_FILES['files']["error"]."<br />";
}
else {
$target = $_SERVER['DOCUMENT_ROOT'].'/images/property-images/';
if (file_exists($target.$currUser.$_FILES['files']['name'])) {
echo $file["name"] . "already exists.";
}
else {
move_uploaded_file($_FILES['files']["tmp_name"],
$target.$currUser.$_FILES['files']["name"]);
echo "Stored in: ".$target.$currUser.$_FILES['files']["name"];
}
}
}
else {
echo 'error';
}
}
$currUser is the current username of the user.
The problem is - when I try to then upload the file. Nothing happens. It echos an error but the filetype is definitely correct. No image is sent to that folder. Where could I be going wrong?
edit - requested var dump:
array(1) {
["files"]=>
array(5) {
["name"]=>
array(1) {
[0]=>
string(17) "Chrysanthemum.jpg"
}
["type"]=>
array(1) {
[0]=>
string(10) "image/jpeg"
}
["tmp_name"]=>
array(1) {
[0]=>
string(14) "/tmp/php1WEAjj"
}
["error"]=>
array(1) {
[0]=>
int(0)
}
["size"]=>
array(1) {
[0]=>
int(879394)
}
}
}
La solution
Excluding count($_FILES['files']['name'])
, you need to add [$i]
to each of your $_FILES
references, e.g., $_FILES['files']["tmp_name"][$i]
.
Also, $file["name"]
should be $_FILES['files']["name"][$i]
.
Autres conseils
for ($i = 0; $i < count($_FILES['file']['name']); $i++) {
if (($_FILES['file']['type'][$i] == "image/jpeg") || ($_FILES['file']['type'][$i] == "image/png") || ($_FILES['file']['type'][$i] == "image/jpg")) {
if ($_FILES['file']["error"][$i] > 0) {
echo "Return Code: ".$_FILES['file']["error"][$i]."<br />";
}
else {
if (file_exists("upload/".$_FILES['file']['name'][$i])) {
echo $_FILES['file']["name"][$i] . "already exists.<br>";
}
else {
move_uploaded_file($_FILES['file']["tmp_name"][$i],
"upload/".$_FILES['file']["name"][$i]);
echo "Stored in: ". "upload/" .$_FILES['file']["name"][$i];
}
}
}
else {
echo 'error';
}
}