Multiple Image Upload PHP form with one input
$error=array();
$extension=array("jpeg","jpg","png","gif");
foreach($_FILES["files"]["tmp_name"] as $key=>$tmp_name) {
$file_name=$_FILES["files"]["name"][$key];
$file_tmp=$_FILES["files"]["tmp_name"][$key];
$ext=pathinfo($file_name,PATHINFO_EXTENSION);
if(in_array($ext,$extension)) {
if(!file_exists("photo_gallery/".$txtGalleryName."/".$file_name)) {
move_uploaded_file($file_tmp=$_FILES["files"]["tmp_name"][$key],"photo_gallery/".$txtGalleryName."/".$file_name);
}
else {
$filename=basename($file_name,$ext);
$newFileName=$filename.time().".".$ext;
move_uploaded_file($file_tmp=$_FILES["files"]["tmp_name"][$key],"photo_gallery/".$txtGalleryName."/".$newFileName);
}
}
else {
array_push($error,"$file_name, ");
}
}
and you must check your HTML code
<form action="create_photo_gallery.php" method="post" enctype="multipart/form-data">
<table width="100%">
<tr>
<td>Select Photo (one or multiple):</td>
<td><input type="file" name="files[]" multiple/></td>
</tr>
<tr>
<td colspan="2" align="center">Note: Supported image format: .jpeg, .jpg, .png, .gif</td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit" value="Create Gallery" id="selectedButton"/></td>
</tr>
</table>
</form>
Nice link on:
PHP Single File Uploading with vary basic explanation.
PHP file uploading with the Validation
PHP Multiple Files Upload With Validation Click here to download source code
PHP/jQuery Multiple Files Upload With The ProgressBar And Validation (Click here to download source code)
How To Upload Files In PHP And Store In MySql Database (Click here to download source code)
PHP Upload Multiple Images through Loop
The problem, I believe having gone through the code properly and tested it lies with the fact that the files are being saved with a new name and that new name is generated using:
$newfilename = round( microtime(true) ) . '.' . end($temp);
When I tested this on a 3 file upload I observed the following when I added some debug statements.
..OK
1630745144.jpg - OK
..OK
1630745144.jpg - OK
..OK
1630745144.jpg - OK
All three were assigned the same name and thus only the last appears to be uploaded as the other two were overwritten.
The debug mentioned was:
$newfilename = round( microtime(true) ) . '.' . end($temp);
if ($uploadOk == 0) {
echo $errorTxt;
} else {
if (move_uploaded_file($_FILES["new_young"]["tmp_name"][$i], $target_dir . $newfilename)) {
echo '..OK<br />';
} else {
$errorTxt = "Sorry, there was an error uploading your file.";
}
echo $newfilename . ' - OK<br />';
}
One would assume that the $errorTxt
here would state the file already exists but it does not because $target_file
and $newfilename
will not be the same. The new name should be generated before the if (file_exists($target_file)) {
check.
So - if you change the relevant code in your original to this the logic test will work but the files will still fail to upload.
$temp = explode(".", $_FILES["new_young"]["name"][$i]);
$newfilename = round( microtime(true) ) . '.' . end($temp);
$target_file = $target_dir . $newfilename;
if (file_exists($target_file)) {
$errorTxt = "Sorry, file already exists.";
$uploadOk = 0;
}
if ($uploadOk == 0) {
// if everything is ok, try to upload file
echo $errorTxt;
} else {
if (move_uploaded_file($_FILES["new_young"]["tmp_name"][$i], $target_file )) {
//echo "The file ". basename( $_FILES["new_young"]["name"]). " has been uploaded.";
} else {
$errorTxt = "Sorry, there was an error uploading your file.";
}
}
The issue now is that $newfilename = round( microtime(true) )
will generate the same integer - a large integer but the same. The precision derived from the microtime is lost so you could modify that to:
$newfilename = str_replace( '.', '', strval( microtime( true ) ) ) . '.' . end( $temp );
With that done all should be well with your code - three images uploaded OK.
upload multiple images at once
Refer to PHP documentation for file uploads
Increase max_file_uploads
By default you'll see this
; Maximum number of files that can be uploaded via a single request
max_file_uploads=20
Also you can update these values,
; Maximum allowed size for uploaded files.
upload_max_filesize = 40M
; Must be greater than or equal to upload_max_filesize
post_max_size = 40M
Upload Multiple Images with PHP and put it into MYSQL Database
Slug is saving as an array, because it is an array.
$slug = $_POST['slug'];
should solve your problem, assuming the slug elements are added in the same order as your files.
As per the comments, the above PHP has been fixed and the fixed HTML below - all I did was remove the array directive from the input:
<form method="POST" action="action-add-images.php" enctype="multipart/form-data">
<input type="hidden" name="slug" value="<?php echo $_GET['slug']; ?>">
<label>Upload Files</label>
<input required type="file" name="image[]" class="form-control-file" multiple>
<button type="submit" class="btn btn-block btn-primary my-3 ">Upload Images</button>
Uploading multiple images and text input with php
Without going into code in great detail, here is generally what you are doing wrong and how you should do it.
The global $_FILES will contain all the uploaded file information. Its contents from the example form is as follows.
Array
(
[img] => Array
(
[name] => Array
(
[0] => bears.jpeg
[1] => big cat.jpeg
[2] => butterfly2.jpeg
[3] => chipmunk.jpeg
)
[type] => Array
(
[0] => image/jpeg
[1] => image/jpeg
[2] => image/jpeg
[3] => image/jpeg
)
[tmp_name] => Array
(
[0] => /tmp/phpNKGKa2
[1] => /tmp/phpOCopiT
[2] => /tmp/phphEGfqK
[3] => /tmp/phpguKfyB
)
[error] => Array
(
[0] => 0
[1] => 0
[2] => 0
[3] => 0
)
[size] => Array
(
[0] => 162804
[1] => 133032
[2] => 118203
[3] => 164941
)
)
)
When you upload files, on the PHP side you will get a structure something like this:
So you have to walk through this structure to get all the files. The form data on the other hand is only stored once in $_POST
.
So you must insert the form data once and the files you must use a loop to go through them all.
// INSERT form data first outside the loop
// Then go through the files in a loop
foreach ($_FILES["img"]["error"] as $key => $error) {
if ($error == UPLOAD_ERR_OK) {
// INSERT file here
$tmp_name = $_FILES["pictures"]["tmp_name"][$key];
$name = basename($_FILES["pictures"]["name"][$key]);
// Usually you have to do this
move_uploaded_file($tmp_name, "some/real/dir");
}
}
Multiple image upload in laravel
change input name
<input type="file" name="image[]" id="files" class="form-control">
controller
public function store(Request $request, $id) {
$request->validate([
'image' => 'required',
]);
$listing = Listing::findOrFail($id);
if ($request->hasFile('image')) {
foreach($request->file('image') as $file)
{
$image = new Listingimage();
$file = $request->file('image');
$extention = $file->getClientOriginalExtension();
$filename = time() . '.' . $extention;
$file->move('assets/images/listingimages/', $filename);
$fileOriginalName = $file->getClientOriginalName();
$image->listing_id = $id;
$image->image_url = $filename;
$image->nom_image = $fileOriginalName;
$image->save();
}
}
return redirect()->back();
}
Related Topics
Checking Browser's Language by PHP
Commenting Interpreted Code and Performance
Select MySQL Rows But Rows into Columns and Column into Rows
PHP Regex for Validating a Url
How to Find Timezone Id from Ip Address/Country Name in PHP
Trying to Replace Parts of String Start with Same Search Chars
Laravel Validation Attributes "Nice Names"
PHP Code Formatter/Beautifier and PHP Beautification in General
PHP Warning: Unknown: Failed to Open Stream
How to Disable Notices and Warnings in PHP Within the .Htaccess File
Why Preg_Replace Throws Me a "Unknown Modifier" Error
Azure Active Directory Sso with Laravel
How to Http Post Special Chars in Swift
Call to Undefined Function MySQLi_Result::Num_Rows()
How to Create Multi-Dimensional Array from a List
How to Efficiently Use Try...Catch Blocks in PHP
Show Progressbar While Loading Pages Using Jquery Ajax in Single Page Website