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++){
Related
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.
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 facing an issue with the below code, I can upload multiple files but still need that the if condition not be executed till user chooses a file as it is not good to see Unique ID and the echo message run however no files chosen!
PHP
<?php
$path = "Uploads/Files/";
if( (isset($_POST['submit'])) && (!empty ($_FILES['myFile']['name'])) ){
$countfiles = count($_FILES['myFile']['name']);
for($i=0;$i<$countfiles;$i++){
$filename = uniqid(). $_FILES['myFile']['name'][$i];
// Upload file
move_uploaded_file($_FILES['myFile']['tmp_name'][$i], $path.$filename);
echo "<h3> $filename has been uploaded Successfully!</h3>";
}
}
?>
So I want the && part above to be valid as well and not below message to appear till files be chosen.
HTML
<form method='post' enctype='multipart/form-data'>
<input type="file" name="myFile[]" id="file" multiple>
<input type='submit' name='submit' value='Upload'>
</form>
Error:
there are two parts:
add validation for required field <input type="file" name="myFile[]" id="file" multiple required>
render whatever you want instead of echo "<h3> $filename has been uploaded Successfully!</h3>";
I'm trying to make a PHP site that uploads files (videos in this case) and displays them. I'm trying to store them in an array and then display them on the page. The problem is, the page is only displaying the last video uploaded, i.e. the array is only storing the last uploaded file. How can I make it so that the array stores the first uploaded file in $array[0], the second in $array[1], and so on... And then display them?
Here's my code (HTML form)
<form action="upload.php" method="POST" enctype="multipart/form-data">
<p>Video to Upload: <br> <input type="file" name="video" /></p>
<p><input type="submit" name="Submit" value="Submit" /></p></form>
PHP code (upload.php)
<?php
$videoname = $_FILES["video"]["name"];
$tmp_name = $_FILES["video"]["tmp_name"];
$thevideos = array();
if (isset($videoname))
{
if (!empty($videoname))
{
$location = 'uploaded/';
move_uploaded_file($tmp_name, $location.$videoname);
$thevideos[] = $videoname; // the array is only storing $videoname in $the videos[0]??
for ($i = 0; $i <= count($thevideos); $i++)
{
echo "<video width=\"320\" height=\"240\" controls>
<source src=\"/uploaded/" .$thevideos[$i]. "\">
</video> <br>";
}
}
else
{
echo "Please choose a file.";
}
}
?>
As mentioned in the comments, if you'd like to get a listing of all files within a directory, you should consider using the scandir or glob functions.
scandir is a good selection if you need to list all content in the directory and glob is a good selection if you need to list files based on wildcards or extensions.
I have a form in which I want to upload at most five images. The name and extension of the images are supposed to be inserted in the database table 'images' and then uploaded to the _uploads/name_of_the_album/ directory.
The problem is, when I choose some images and hit upload, only the first image is uploaded correctly, the other images fail.
Here is my code:
if(isset($_FILES['image']) === true){
$files = $_FILES['image'];
$allowed_ext = array('jpg', 'jpeg', 'png', 'gif');
$album_id = (int)$_GET['album_id'];
$album_name = $_GET['album_name'];
for($i=0; $i<count($files['name']); $i++){
$name = $files['name'][$i];
$tmp_name = $files['tmp_name'][$i];
$size = $files['size'][$i];
$ext = explode('.', $files['name'][$i]);
$ext = strtolower(end($ext));
$img_name = explode('.', $files['name'][$i]);
$img_name = strtolower(current($img_name));
//do some testing echos to see the result
//echo $img_name."<br>";
//here i'm going to add some validation as soon as
// i fix the multi-upload problem
//insert image into database
$query_insert_image = "INSERT INTO `images` (album_id, image_name, image_ext) VALUES ({$album_id}, '{$img_name}', '{$ext}') ";
$insert_image = mysql_query($query_insert_image, $connection) or die(mysql_error());
if(mysql_affected_rows() == 1){
move_uploaded_file($tmp_name, '../_uploads/'.$album_name.'/'.$name);
}
//redirect
redirect_to("view_album.php?succeed=1");
}//end the for loop
//echo '<pre>',print_r($files, true),'</pre>';
}
And here is some of the code of the form:
<form action="" method="post" enctype="multipart/form-data" name="formUploadImages" id="formUploadImages">
<p>
<label for="image">Choose one or more Image(s):</label><br />
<input type="file" name="image[]" id="image" /><br />
<input type="file" name="image[]" id="image" /><br />
<input type="file" name="image[]" id="image" /><br />
<input type="file" name="image[]" id="image" /><br />
<input type="file" name="image[]" id="image" />
</p>
......
Any ideas what I'm doing wrong?
I think you're cutting the branch from under your own feet.
redirect_to("view_album.php?succeed=1");
Redirecting means refreshing the page which means the end of execution. When that redirect is triggered after the first for loop ends and first image is uploaded the for will not continue to the next iteration.
And the fix of course is to push that line after the for loop (and never expect anything after a redirect to ever execute - unless the headers are already sent).
Most functions that do what redirect_to() does (it's not a core function it's based on another function header()) also make sure execution stops (have a line calling header() and another line calling die()/exit()).
try this php code ,working for me:
for($i=1;$i<6;$i++)
{
if(!empty($_FILES['image_upload'.$i])):
$target = "images/".$_FILES['image_upload'.$i]['name'];
$image_upload.= ",".mysql_real_escape_string(($_FILES['image_upload'.$i]['name']));
move_uploaded_file($_FILES['image_upload'.$i]['tmp_name'], $target);
endif;
}
create a folder in your root named "images" ,all the images will be moved in this folder.
html form may be looks like:
<form action="" method="post" enctype="multipart/form-data" name="formUploadImages" id="formUploadImages">
<p>
<label for="image">Choose one or more Image(s):</label><br />
<input type="file" name="image_upload1" id="image_upload1" /><br />
<input type="file" name="image_upload2" id="image_upload2" /><br />
<input type="file" name="image_upload3" id="image_upload3" /><br />
<input type="file" name="image_upload4" id="image_upload4" /><br />
<input type="file" name="image_upload5" id="image_upload5" />
</p>
......
this code is running on my end ,and after some editing as according to your needs may be useful for you.
Happy coding!
foreach($_POST['image'] as $report_id){
$sql="INSERT INTO images (album_id, image_name, image_ext) VALUES ('{$album_id}', '{$report_id}', '{$ext}') ";
$queryExe=mysql_query($sql);
}
replace this code in the place of your code after "//insert image into database" .
http://php.net/manual/en/features.file-upload.multiple.php
Read the Warning block 'Since PHP 5.2.12, the max_file_uploads configuration...'. Maybe that's the problem.
And there are some good examples and maybe You should use foreach instead of for.
1) Create a .htaccess file in the root folder of web server.
2) Put the following code in side the .htaccess file and save it.
php_value upload_max_filesize 20M
php_value post_max_size 20M
php_value max_execution_time 200
php_value max_input_time 200
Now you can upload the file-size up-to 20MB in a simple way using file field in your html form and move_uploaded_file() function available in PHP.