Multiple upload fields PHP - 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]);
}
?>

Related

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++;
}
}

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.

How can I know a number of uploaded files with 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']);

How to upload multiple files in PHP

All the scripts I have found via Google search rely on some sort of screen that first asks the user how many files they need to upload and the upload script works based on that number.
But what if I don't want any limits, but want to allow the user to upload as many or as few as they want. How to go about this?
All I have for now is the form:
<form enctype="multipart/form-data" method="post" action="script.php">
<input id="my_file_element" type="file" name="myFile[]" >
<input type="submit" value="Upload!" name="submit">
</form>
EDIT
I think the way I phrased my question is causing some misunderstanding. I am not in need of some way to add more "input type = file" field elements. I am already using a javascript that enables the user to add more form fields by clicking a button, those other fields are identical to the 1st one posted above.
What I am asking this question for, is to know how to handle the actual upload of files to the server using a php script.
EDIT
Let's say your form is like this
<form enctype="multipart/form-data" method="post" action="script.php">
<input id="my_file_element" type="file" name="myFile[]" >
<input id="my_file_element" type="file" name="myFile[]" >
<input id="my_file_element" type="file" name="myFile[]" >
etc...
<input type="submit" value="Upload!" name="submit">
</form>
What you want to do is get all the files called myFile[]. Here's what you do in PHP:
foreach ($_FILES["myFile"]["error"] as $key => $error) {
if ($error == UPLOAD_ERR_OK) {
$tmp_name = $_FILES["myFile"]["tmp_name"][$key];
$name = $_FILES["myFile"]["name"][$key];
// here we move it to a directory called data
// you can move it wherever you want
move_uploaded_file($tmp_name, "data/$name");
} else {
// an error occurred, handle it here
}
}
ORIGINAL
Using HTML and JavaScript alone, there isn't any easy way to upload multiple files at the same time.
I would use a Flash library, such as SWFUpload, to do the upload instead. Using this plugin, you can show a standard multi-file upload window, as shown in this demo. This will allow users to easily select multiple files in the same file browser.
If you don't want to use Flash for some reason, you could use JavaScript to dynamically swap input elements, as in this example.
EDIT
That depends on how you called the file input elements. If you followed my approach below, you can get the number of files with:
if (empty($_FILES['attach']['name']))
$count_files = 0;
else
$count_files = count($_FILES['attach']['name']);
Try var_dump($_FILES) to see the complete $_FILES array, in case you have any doubts on its structure.
ORIGINAL
Something like this, with Javascript:
<script type="text/javascript">
var j = 2; //default two files
function novoa() {
j = j+1;
var elem = document.createElement("input");
var par = document.getElementById("filed");
elem.setAttribute("type", "file");
elem.name = "attach[]";
elem.id = "file_" + j;
par.appendChild(elem);
}
function delult() {
if (j == 0) return;
var elem = document.getElementById("file_" + j);
var par = document.getElementById("filed");
j = j-1;
par.removeChild(elem);
}
</script>
...
<p id="addupl">More files |
Less files</p>
<p id="filed">
<input type="file" name="attach[]" id="file_1" />
<input type="file" name="attach[]" id="file_2" />
</p>
OMG you're asking how to handle this form?
there is an example right on the manual page:
http://www.php.net/manual/en/features.file-upload.post-method.php
<?php
foreach ($_FILES["pictures"]["error"] as $key => $error) {
if ($error == UPLOAD_ERR_OK) {
$tmp_name = $_FILES["pictures"]["tmp_name"][$key];
$name = $_FILES["pictures"]["name"][$key];
move_uploaded_file($tmp_name, "data/$name");
}
}
?>
In your PHP script, do a var_dump($_FILES). The output should help you move further into the direction you wish. Take a look at PHP's filesystem functions for more info on what you can do with the files, after using the move_uploaded_file function.
In order to really answer your question How to handle the upload, you'd need to tell us what you want to accomplish/do with the files.
Just use JavaScript to append another input element to the form.

Categories