Error in image uploading and renaming in php
Form
<form action="product.php" method="post" enctype="multipart/form-data">
<input type="file" name="image" multiple>
<input type="submit" value="Add Product" name="submit" >
</form>
product.php
$image = $_FILES['image'];
$i = 1 ;
foreach ($image as $new_image)
{
print_r($new_image);
echo '<br>';
$dir_path_up = 'assets/images/product_images/'.$model."/";
$target_file = $dir_path_up . basename($new_image);
$new_name= $dir_path_up .$i.".jpg";
move_uploaded_file($_FILES["image"]["tmp_name"], $new_name);
$i++;
}
I used above code to Rename image and upload image to specific($model) directory. All looks perfect, when upload a single image. But when I upload more than Single Image, last image only get rename and Upload. (Example : If i upload 3 image, last image get only upload and it get rename as1.jpg
. and rest of previous images are not getting upload.)
Is some thing wrong in this?? I get Struck on this.
Answer
Solution:
When you are uploading the images the last image will be uploaded only the reason being you are not handling it correctly. Try
print_r($_FILES)
before this to see the actual structure.You need to use
<input type="file" name="image[]" />
The sample structure you should have:
Array (
)
Then you can handle it suitably.
Answer
Solution:
Try this code:
First problem is with name of the
input(type= file)
field you have taken for uploading file. your form is actually uploading only one file which was selected in the end. That is why you are facing that problem.So solve this rename it as
image[]