I have a php image upload code that doesn't upload the image.
PHP
if (isset($_FILES['file']) && $_FILES['file']['error']==0) {
$files = $_FILES['file'];
echo $tmp_name = $files['tmp_name'];
$moved=move_uploaded_file($tmp_name,"../a.jpg");
if($moved){
echo'Done!';
}
}else{
echo 'Error uploading, code '.$_FILES['file']['error'];
}
HTML
<form method="post" enctype="multipart/form-data" action="samefile.php">
<input type="file" name="file">
<input type="file" name="file">
<input type="submit" value="submit">
</form>
This is the simplified form of my code. In the real scenario there are multiple upload button but only one button can be used at once.
The problem is that it shows the error Error uploading, code 4
.
Please help.
Thanks
Try this code, this will work for you to upload multiple files you need to use name="file[]"
instead of name="file"
this will submit all the files in array and you can loop each file using for loop in php file..
<form method="post" enctype="multipart/form-data" action="samefile.php">
<input type="file" name="file[]" >
<input type="file" name="file[]" >
<input type="submit" value="submit">
</form>
In php file
<?php
if (isset($_FILES['file']))
{
$total = count($_FILES['file']['name']);
for($i=0; $i < $total; $i++)// Loop for each file
{
$tmp_name = $_FILES['file']['tmp_name'][$i];
if ($tmp_name != "")
{
$targetFile = "../" . $_FILES['file']['name'][$i];
//Upload the file
if(move_uploaded_file($tmp_name,$targetFile))
{
echo'Done!';
}
}
}
}
?>