问题
I am currently working on a website project, and need to have more than one image uploaded in the same form.
When the form is submitted, only the last picture is uploaded, and I can't figure out why. I've been looking on an answer on Google, this website and many others, but I couldn't find anyone with exactly the same problem to find a solution.
I have tested this basic code both with WAMP and online, and the problem remains the same...
Here's the form :
<form action="index.php?action=add" method="post" enctype="multipart/form-data">
<input type="file" name="file1"/><br/>
<input type="file" name="file2"/><br/>
<input type="file" name="file3"/><br/>
<input type="hidden" name="add" value="1"/>
<input type="submit" value="ok"/>
And here is the code I use for the upload :
function move_avatar($avatar)
{
$extension_upload = strtolower(substr( strrchr($avatar['name'], '.') ,1));
$name = time();
$nomavatar = str_replace(' ','',$name).".".$extension_upload;
$name = "images/".str_replace(' ','',$name).".".$extension_upload;
move_uploaded_file($avatar['tmp_name'],$name);
return $nomavatar;
}
if(!empty($_POST['add'])){
for($i=1;$i<=3;$i++){
if(!empty($_FILES['file'.$i]['size'])){
$extensions_valides = array( 'jpg' , 'jpeg' , 'gif' , 'png', 'bmp' );
$extension_upload = strtolower(substr(strrchr($_FILES['file'.$i]['name'], '.') ,1));
if(in_array($extension_upload,$extensions_valides))
$img =(!empty($_FILES['file'.$i]['size']))?move_avatar($_FILES['file'.$i]):'';
else $img = 'defaultImg.png';
}else $img = 'defaultImg.png';
}
print_r($_POST);
}else include('test.php');
Any ideas ? :/
回答1:
it's Caroline from Facebook !
Even if you read my answer on Facebook, I post this answer to indicate that this problem is solved.
After testing your script, I found what's wrong. The problem is located in your function, where you declare the $name variable :
$name = time();
When you upload several pics at the same time, they all have the same timestamp and thus, the same name ! That's why only the last pic is sent !
To fix this, I added an argument in your function in order to add a digit that will make the filenames different from each other :
function move_avatar($avatar,$number)
Then I added this new variable to the first $name variable :
$name = time().$number;
And finally, I use the $i variable when the function is used :
$img =(!empty($_FILES['file'.$i]['size']))?move_avatar($_FILES['file'.$i],$i):'';
With these modifications, all images uploaded have now a distinct name, the last digit being different.
来源:https://stackoverflow.com/questions/20164776/multiple-upload-only-the-last-file-is-uploaded