I have the below code which works perfectly and compressing 1 image at a time, however, I would like to have this loop so that it can handle multiple images at any one time.
<form method="post" action="" enctype="multipart/form-data">
<div class="file-upload-wrapper">
<input type="file" name="image" accept="images" multiple>
</div>
<input type="submit" value="upload" name="submit">
</form>
<?php
if (isset($_POST['submit'])) {
$image_name=$_FILES['image']['name'];
$tmp_name=$_FILES['image']['tmp_name'];
$directory_name='uploads/'; //folder where image will upload
$file_name=$directory_name.$image_name;
move_uploaded_file($tmp_name, $file_name);
$compress_file="og_optimised--".$image_name;
$compressed_img=$directory_name.$compress_file;
$compress_image=compressImage($file_name,$compressed_img);
unlink($file_name); //delete original file
}
function compressImage($source_image,$compress_image) {
$image_info=getimagesize($source_image);
$compression_level = $_POST["compression"];
if ($image_info['mime']=='image/jpeg') {
$source_image=imagecreatefromjpeg($source_image);
imagejpeg($source_image,$compress_image,60); //for jpeg or gif, it should be 0-100
}
elseif ($image_info['mime']=='image/png') {
$source_image=imagecreatefrompng($source_image);
imagepng($source_image,$compress_image,3); //for png it should be 0 to 9
}
return $compress_image;
}
?>
Any help is greatly appreciated, thank you :)
I have attempted to use a loop statement but cant seem to get it working, likely my lack of PHP knowledge.
Related
I need to upload a lot of images at once (e.g. 200 small images) through the browser. I have this code:
<?php
if(isset($_POST['Upload_files']) and $_SERVER['REQUEST_METHOD'] == "POST"){
echo count($_FILES['files']['name']); // Even if I upload more than 20 files, it still displays 20.
$target_directory = "upload/";
foreach ($_FILES['files']['name'] as $file_number => $file_name) {
$file = $_FILES["files"]["tmp_name"][$file_number];
if (mime_content_type($file) != 'image/png' && mime_content_type($file) != 'image/jpeg')
{ $error[] = 'File '.$file_name.' is not in JPG / PNG format!'; continue; }
else
{ if(move_uploaded_file($file, $target_directory.$file_name)) {$count_of_upload_file++;}}
}
}
// If files were uploaded
if($count_of_upload_file != 0){echo 'Your files ('.$count_of_upload_file.' ) were successfully uploaded.';}
// If there was an error
if (isset($error)) {foreach ($error as $display_error) {echo '- '.$display_error.'<br />';}}
?>
<form action="" method="post" enctype="multipart/form-data">
<input type="file" name="files[]" multiple="multiple" accept="image/*">
<input type="submit" name="Upload_files" value="Upload files">
</form>
And it works. However my provider set the 'max_file_uploads' to 20 (and I'm not able to change it). (The Uploadify extension is working for more than 20 files, but I'd like to have my own small solution.) So I presume I need to add here something, which instead of 200 files at once uploads 200 files one by one (or twenty by twenty). But I don't know how to do it. (To use AJAX? -- I never used it, so I really don't know.) Thank you!
If you don't want to use ajax, you need a loop to receive files
for($i = 0; $i < count($_FILES['files']['tmp_name']); $i++){
$tmp = $_FILES['files']['tmp_name'][$i];
$name = md5(microtime());
if(move_uploaded_file($tmp, "dir/$name.jpg")){
echo "Uploaded successfully";
}else{
echo "failed";
}
}
In your form you must name all your input fields as files[], example:
<form action="" method="post" enctype="multipart/form-data">
<input type="file" name="files[]" multiple="multiple" accept="image/*">
<input type="file" name="files[]" multiple="multiple" accept="image/*">
<input type="file" name="files[]" multiple="multiple" accept="image/*">
<input type="submit" name="Upload_files" value="Upload files">
</form>
Or if you want to use ajax here is an example:
Upload multiple image using AJAX, PHP and jQuery
HTML in 'index.php':
<form action="index.php" method="post" enctype="multipart/form-data">
<input type="file" name="fileToUpload" id="fileToUpload" accept="application/pdf, .pdf" required><br>
<input type="submit" name="submit" value="SUBMIT">
</form>
PHP in 'index.php':
<?php
if (isset($_POST['submit'])) {
$target_dir = 'docs/';
$temp_loc = $_FILES['fileToUpload']['tmp_name'];
$file = $_FILES['fileToUpload']["name"];
if(move_uploaded_file($temp_loc,$target_dir.$file)) {
?><script>alert('successfully uploaded');</script><?php
} else {
?><script>alert('error while uploading file');</script><?php
}
}
?>
The following code doesn't seem to upload any of the documents I select to the target dircetory, that is, '/docs'.
I'm using wampserver with localhost, if that is needed at all. The 'file-upload' is allowed in the 'php.ini'
I've seen many tutorials and have even done troubleshooting on Stackoverflow itself, but I can't seem to make it work.
Thanks in advance
How can i count the number of uploaded files?
This is my form:
<div id="dragAndDropFiles" class="uploadArea">
<h1>Drop Images Here</h1>
</div>
<form id="sfmFiler" class="sfmform" method="post" enctype="multipart/form-data">
<input type="file" name="file" id="file" multiple />
<input type="submit" name="submitHandler" id="submitHandler" class="buttonUpload" value="Upload">
</form>
and this is the piece of php which uploads the files:
if($_SERVER['REQUEST_METHOD'] == "POST") {
$tmpFilePath = $_FILES['file']['tmp_name'];
$newFilePath = $dir.'/' . $_FILES['file']['name'];
if(move_uploaded_file($tmpFilePath, $newFilePath)) {
echo "xxx files are successfully uploaded";
}
}
In this code you are getting only one file thats why you are getting count result 1. if change your input file name like "file[]"
<input type="file" name="file[]" id="file" multiple />
and then use the below line code you will get your desire result. Cause its needs an array filed to hold the input data.
<?php echo count($_FILES['file']['name']); ?>
Thanks, i tried in my system get the result.
AFriend is correct. The above answers always return 1.
Try:
echo count(array_filter($_FILES['file']['name']))
Worked for me anyway.
_t
Using the array_filter function it works
try
$countfiles = count(array_filter($_FILES['file']['name']));
It returns 0 in case of NULL, 1 in case of 1 file uploaded, etc.
Check this answer
<?php echo count($_FILES['file']['name']); ?>
php multiple file uploads get the exact count of files a user uploaded and not the count of all input fields in the array
You could use the count function:
$no_files = count($_FILES);
If no files are selected and your file count is 1, you can use this line before moving the file:
if (!empty($_FILES['file']['tmp_name'][0])) {
for($i=0;$i<$countfiles;$i++){
I am trying to get image file name by tag, But when I check it through isset($_FILES['imgFile']), it returns always false.
Here is my HTML tag for getting image file:
<input type="file" name="imgFile" accept="image/*" id="imgFile" src=""/>
Here is my php code to retrieve it:
if(isset($_FILES['imgFile']))
{
$img = $_FILES['imgFile']['name'];
echo $img";
}
else
{
echo "Image not set";
}
It always generate "Image not set" as an output though I have selected an image.
Are you using the correct enctype on the form?
<form enctype="multipart/form-data">
This is required when using a file upload element.
just use:
enctype="multipart/form-data"
Say this is your form:
<form action="same_page.php" method="post" enctype="multipart/form-data">
<input type="file" name="imgFile" accept="image/*" id="imgFile" src=""/>
<input type="submit" name="upload" value="Upload" />
</form>
and your php code to retrive name of the image is in the same page where the form is, then your code should be like this:
<?php
if (isset($_POST["upload"])) {
if (isset($_FILES['imgFile'])) {
$img = $_FILES['imgFile']['name'];
echo $img;
} else {
echo "Image not set";
}
}
?>
But if your php code is in another page, then you only need to use enctype="multipart/form-data" in the form as mentioned in the other answers.
I have ZERO experience coding uploading files through browser, so this part is all very new to me.
I need to give users (in fact they will be only one or two authorized users) a way to upload multiple text files (think 50-200 files) directly into a MYSQL database.
I don't want to give them FTP access, but am OK allowing them to enter files into the database.
I can figure out how to get the data from a PHP array into the MYSQL database.
What I can't figure out is how to get the contents of multiple files into the PHP array(s).
Please help out with the code.
This example should help you understand the basic idea
<?php
$fileContents = Array();
if(count($_FILES) != 0){
foreach($_FILES as $file){
$fp = fopen($file["tmp_name"], "r");
array_push($fileContents, fread($fp, $file["size"]));
fclose($fp);
}
//$fileContents now holds all of the text of every file uploaded
}
?>
<html>
<head>
</head>
<body>
<form action="test.php" method="post" enctype="multipart/form-data">
<input type="file" name="file1" id="file" />
<input type="file" name="file2" id="file" />
<input type="submit" name="submit" value="Submit" />
</form>
</body>
</html>
It first checks that there has been files posted to itself.
If there is files, it loops through each and opens them while they are in their temporary file state.
After that it reads all of the contents at once (be careful with this) using the size attribute that sent with it.
At the same time, it is pushing the contents into the array called $fileContents.
So $fileContents[0] holds the first text file and so on.
Just add more <input type="file">s to your page, and they will all appear in the $_FILES array, which you can loop to retrieve them.
However:
The structure of the $_FILES array is slightly illogical when it comes to multiple files - make sure you read the manual carefully, it is a little counter intuitive.
Make sure that your upload_max_filesize, post_max_size, max_file_uploads and max_input_time PHP.ini directives are generous enough.
See also: Handling multiple file uploads in PHP.
<!-- FORM -->
<form method="post" enctype="multipart/form-data">
<?php
for($i=1;$i<=10;$i++) //change 10 to any number for more upload fields
{
echo '<input type="file" name="files[]" /><br />';
}
?>
<input type="submit" name="submit" value="Submit" />
</form>
<?php
//Processor
if(isset($_POST['submit']))
{
foreach($_FILES['files']['tmp_name'] as $tmp_name)
{
if(!empty($tmp_name))
{
$filecontent[] = file_get_contents($tmp_name);
}
}
//Test
echo '<pre>';
print_r($filecontent);
echo '</pre>';
}
?>
Thank you everyone who has contributed to this. I am having a very hard time choosing the answer, because I think it's a 50/50 effort by John and DaveRandom.
In case someone wants to see the end product here it is:
HTML:
<html>
<head>
</head>
<body>
<form method="post" action="test.php" enctype="multipart/form-data">
<input name="filesToUpload[]" id="filesToUpload" type="file" multiple="" />
<input type="submit" name="submit" value="Submit" />
</form>
</body>
</html>
PHP:
<?php
function rearrange( $arr ){
foreach( $arr as $key => $all ){
foreach( $all as $i => $val ){
$new[$i][$key] = $val;
}
}
return $new;
}
$fileContents = Array();
if(count($_FILES['filesToUpload'])) {
$realfiles=rearrange($_FILES['filesToUpload']);
foreach ($realfiles as $file) {
$fp = fopen($file["tmp_name"], "r");
array_push($fileContents, fread($fp, $file["size"]));
fclose($fp);
}
foreach ($fileContents as $thisone) {
echo "<textarea wrap='off'>\n";
echo $thisone;
echo "</textarea>\n";
echo "<br>----<br>";
}
}
?>