How can I know a number of uploaded files with PHP? - php

I have a form with several
input type="file"
tags. How can I know on the server side amount of files uploaded by the user. He can upload 3 files, or may be 5 files, 1 or even nothing. I need to know how much files user have uploaded.

You can use the count or sizeof on $_FILES array that contains uploaded file info:
echo count($_FILES);
Update (Based on comments):
You can do this:
$counter = 0;
foreach($_FILES as $value){
if (strlen($value['name'])){
$counter++;
}
}
echo $counter; // get files count

If you are having input upload tags with name like file1, file2 then
if($_FILES['file1']['size'] > 0)
echo "User uploaded some file for the input named file1"
Now for many files (looking at the output you are having), run a foreach loop like this:-
$cnt=0;
foreach($_FILES as $eachFile)
{
if($eachFile['size'] > 0)
$cnt++;
}
echo $cnt." files uploaded";
I am not sure why the similar answer in How can I know a number of uploaded files with PHP? got downvoted? For the '0' ?

$_FILES is a global array of files which stores uploaded files.

Form:
<form enctype="multipart/form-data" ...>
<input type="file" name="image[]" multiple>
Script:
$c = sizeof($_FILES['image']['name']);

Related

numerous errors handling file upload in php

I'm using this code to process uploaded files:
mkdir("files/" . $id, 0700);
$path = "files/" . $id;
$count = 0;
if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST")
{
foreach($_FILES['attachments']['name'] as $f => $name)
{
if($_FILES['attachments']['error'][$f] == 4)
{
continue;
}
if($_FILES['attachments']['error'][$f] == 0)
{
if(move_uploaded_file($_FILES["attachments"]["tmp_name"][$f], $path.$name))
{
$count++;
}
}
}
}
$id is a random number taken from the database. Besides, I'm using this markup:
<input type="file" id="attachments" name="attachments[]" multiple="multiple" accept="*">
While the exact same code had worked brilliantly before, it now throws numbers of errors I can't really deduce:
1: mkdir(): File exists in ... on line ... (<-- now, it doesn't for granted!)
2: Undefined index: attachments in ... on line ... (well, it's defined also using form method post!)
3: Invalid argument supplied for foreach() in ... on line ... (which is quite clear as the above stated errors do prevent the foreach from doing its job correctly)
Yes, I made sure that I'm actually using POST. I also tried changing the file input's name from attachments to any other, however, scenario remains the same.
Adding enctype="multipart/form-data" has done it.
1] Check for the folder rights 0777. Weather you are able to create directory or not
2] After posting form. Make sure your form has enctype = multipart/form-data tag.
In you file please check with
echo "<pre>";
print_r($_FILES);
exit;
If you are getting any data or not? If getting data then move ahead.
First check if your $id really contain something, secondly your form should have attribute of enctype = multipart/form-data for using input type file.
<form action="test.php" method="post" enctype="multipart/form-data">
Now in your case you will get the array of files you before your perform any work, see print_r of attachments:
echo "<pre>";
print_r($_FILES);
exit;

File upload php, get only file name

Is it possible to get the filename of a file, without a complete upload
Meaning after the user chose a file, dont upload that file, just get the filename and save to database?
yes it is possible you can use the code as given below
$filename=$_FILES['nameofyourfileinput']['name'];
echo $filename;
you can echo the $filename;
OR You can use jquery to get this value like
$('#inputid').change(function(){
var value =$(this).val();
alert(value);
})
ya it is possible.You can also do this before uploading the file basename() is enough for extracting name.
$next=$pfet['f_name']; //fetched file from database
$next1 = basename($next);
The accepted answer doesn't prevent the file upload, it simply provides a way to get the file name independent of the file contents.
Preventing file upload, is best looked at the other way: what enables uploading a file. The answer to that is the enctype attribute on the form tag (multipart/form-data).
HTML:
<form action="upload.php" method="post" enctype="application/x-www-form-urlencoded">
Select:
<input name="upload[]" type="file" multiple="multiple" />
<input type="submit" value="Update" name="submit">
</form>
PHP:
$total = count($_POST['upload']);
// Loop through each file
for( $i=0 ; $i < $total ; $i++ ) {
$fileName = $_POST['upload'][$i];
}

php multiple file uploads get the exact count of files a user uploaded and not the count of all input fields in the array

Ok. I give up on this. When uploading multiple files to the server using php, what is a fail safe method to return the count of files the user has actually uploaded?
Whatever I have done so far, returns the count of all the fields in the form, and the count of the files a user uploads. So if the total fields in the form were 3 and a user uploaded only 2 files, I still get 3 as the count of file uploaded.
One place suggested using array_filter to do this, but that's totally beyond me.
echo count($_FILES['file']['tmp_name']); //3
echo count($_FILES['file']); //3
Any fail safe method you follow and can suggest other than looping through the FILES array size to check for this?
My form is structured like any other:
<form action="process.php" method="post" enctype="multipart/form-data">
<div><input type="file" name="file[]"></div>
<div><input type="file" name="file[]"></div>
<div><input type="file" name="file[]"></div>
<div><input type="submit"></div>
</form>
Exactly as they told you, just simply use array_filter().
echo count(array_filter($_FILES['file']['name']));
It will return the right number
$count = 0;
foreach($_FILES as $file) {
if(isset($file["file"]["tmp_name"]) && !empty($file["file"]["tmp_name"]))
$count++;
}
Try this
$count = 0;
$fileCount=count($_FILE['file']['name'];)
$fileSize=$_FILES['file']['size'];
for($i=0;$i<$ fileCount;$i++) {
if ($fileSize[$i] > 0) {
$count++;
}
}

Multiple upload fields PHP

My question is, how and will <input type='file' name='file[]'> multiple of theese work in php?
Thanks
If you loop through them as an array, it'll work just the same:
foreach($_FILES['file'] AS $key=>$file) {
$filename = $file['tmp_name'];
$size = $file['size'];
$newfile = $_SERVER['DOCUMENT_ROOT'] . "/uploads/" . date("Ymd_his") . "_" . $filename;
move_uploaded_file($filename, $newfile);
}
And it'll loop through each upload and process as such.
Just be sure that you have something that changes between each (I added a timestamp) - otherwise you'll only end up with one file.
You were right with the inputs as
<input type="file" name="file[]" />
You can have as many of those as you'd like
Yes they'll work. $_FILES will be an array of uploaded files in PHP.
Yes this will of course work. Just have a look at the $_FILES superglobal array. All your uploaded files and their meta data will be stored there.
According to the W3C's HTML5 draft, you should add the multiple attribute :
<input type="file" name="file[]" multiple="multiple">
Some browser (like Internet Explorer (even 9)) don't support multiple attribute but major other ones does.
Then, you can get all the file by looping into the $_FILES superglobal like that :
<?php
foreach ($_FILES['file']['error'] as $k => $error) {
if (!$error) {
move_uploaded_file($_FILES['file']['tmp_name'][$k], $your_dir.'/'.$_FILES['file']['name'][$k]);
}
}
?>
As far as I am able to tell, if you want to do multiple file uploads from a html form, you need to have multiple file input boxes.
<input type='file' name='file1'>
<input type='file' name='file2'>
<input type='file' name='file3'>
Unless you have some type of java, javascript, flex, or similar multiple file upload framework to do the work for you.
Once you get it uploaded, the PHP script would look like:
<?
foreach($_FILES as $file){
move_uploaded_file($file[tmp_name],$target.$file[name]);
}
?>

PHP: multiple files upload without ajax

I want any php script which can demonstrate me how to upload multiple files in PHP. In my application I have given a link "Add Image" & 'Remove Image', on click of "Add Image" I am adding a new upload field on the page using javascript, using which user can upload more and more images, no limit on number of images for now. On click of delete i am removing that element.
I am just not getting the concept on how to process them in the POST request in PHP. I know in HTML if we give the name of field like myimages[] then it will create a PHP array, but how to process this.
I don't want to use AJAX/JavaScript for uploading, want to do it with traditional POST request in PHP.
If anyone have any link or code which shows such functionality, then pleas provide it will be really helpful.
Thanks!
combine this uploading multiple files & move_uploaded_file
<form action="file-upload.php" method="post" enctype="multipart/form-data">
Send these files:<br />
<input name="userfile[]" type="file" /><br />
<input name="userfile[]" type="file" /><br />
<input type="submit" value="Send files" />
</form>
$uploads_dir = '/uploads';
foreach ($_FILES["userfile"]["error"] as $key => $error)
{
if ($error == UPLOAD_ERR_OK)
{
$tmp_name = $_FILES["userfile"]["tmp_name"][$key];
$name = $_FILES["userfile"]["name"][$key];
move_uploaded_file($tmp_name, "$uploads_dir/$name");
}
}
Uploaded files are not in the POST array, they are in the FILES array.
http://www.php.net/manual/en/features.file-upload.multiple.php
The files are uploaded to a temp area with "safe" names. The array will contain the name of the file and the tmp file. You can then move them to where you want.
Name file input fields as file[] in HTML, then just run a loop from 0 do count($_FILES) in PHP...
for($i = 0; $i < count($_FILES['file']['tmp_name']); $i++){
$tmp = $_FILES['file']['tmp_name'][$i];
$name = md5(microtime());
if(move_uploaded_file($tmp, "dir/$name.jpg")){
echo "File '$tmp' uploaded successfully";
}else{
echo "Uploading '$tmp' failed";
}
}
I've implemented something similar in the past as follows:
Have a hidden JavaScript form variable (e.g.: "numuploads") that stores the number of file inputs currently in the form. This will need to be incremented/decremented when you add/remove an input on the front end.
Name each of the inputs on the front end using a pattern such as "upload_X", where X is the next in the sequence. (Effectively the same as the counter above -1.)
On the PHP landing page, simply scan the $_FILES superglobal, looking for each "upload_X" where X is zero thru numuploads - 1.
You can then carry out the required logic for each of the uploaded files, other form elements, etc.

Categories