PHP Uploading: Uploading multiple files? - php

I'm currently uploading a single file successfully with the following form:
<html>
<body>
<form action="upload_file.php" method="post" enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="file" id="file" />
<br />
<input type="submit" name="submit" value="Submit" />
</form>
</body>
</html>
And with the following script:
<?php
error_reporting(E_ALL);
if (($_FILES["file"]["size"] < 20000))
{
if ($_FILES["file"]["error"] > 0)
{
echo "Return Code: " . $_FILES["file"]["error"] . "<br />";
}
else
{
echo "Upload: " . $_FILES["file"]["name"] . "<br />";
echo "Type: " . $_FILES["file"]["type"] . "<br />";
echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />";
echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br />";
$moved = move_uploaded_file($_FILES["file"]["tmp_name"], "C:/inetpub/wwwroot/PHP_Ramp/upload/" . $_FILES["file"]["name"]);
if ($moved) {
echo "Move: Success <br/>";
}
else {
echo "Move Failed <br/>";
}
echo "Stored in: " . "C:/inetpub/wwwroot/PHP_Ramp/upload/" . $_FILES["file"]["name"];
}
}
else
{
echo "Invalid file";
}
?>
I'm now trying to allow the user to select three different files from the form. I've found a few guides that show how to do something similar, but I can't quite get it working.
I've modified the form as follows (to include three inputs):
<html>
<body>
<form action="upload_file.php" method="post" enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="file" id="file" />
<input type="file" name="file" id="file" />
<input type="file" name="file" id="file" />
<br />
<input type="submit" name="submit" value="Submit" />
</form>
</body>
</html>
But I'm not sure how to modify the php to handle all three files. I know I need to iterate through _FILES but everything I've tried isn't working. Any pointers would be appreciated.

Each file element must have a unique name, or use PHP's array shorthand:
<input type="file" name="file1" />
<input type="file" name="file2" />
or
<input type="file" name="file[]" />
<input type="file" name="file[]" />
Remember - the name attribute defines how you'll identify that field on the server, and if you use the same name multiple times, PHP will overwrite previous copies with the latest one as it parses through the submitted data. The array notation ([]) tells PHP that you INTENDED to have multiple fields with the same name, and that each copy it finds should be added to an array, not overwritten.
For the unique name version, you'd handle each as you are right now with the single file.
For the array version, PHP has a design stupidity that requires slightly different handling. You end up with a $_FILES array that looks like
$_FILES = array(
'fieldname' => array(
'name' => array(
0 => 'first file',
1 => 'second file',
etc...
)
)
)

You need to change
<input name="file" />
to
<input name="file[]" />
To make them into an array.
Then in your script, you reference them as:
$_FILES['file']['name'][0]; // first file
$_FILES['file']['name'][1]; // second file
Note you can replace name with any of the other file properties that you usually would use on a single file (e.g. size, type etc).
Alternatively, you can give them all different names:
<input name="firstfile" />
<input name="secondfile" />
Then in your script:
$_FILES['firstfile']; // first file
$_FILES['secondfile']; // second file

You can select multiple file in single input like this..
<input type="file" name="pic[]" id="pic" accept="image/*" multiple="multiple"/>
This input box can accept multiple files by pressing control key. Now you can access them in php like this
$_FILES['file']['name'][0]; // first file
$_FILES['file']['name'][1]; // second file

KISS Code with some explanations:
There is fully functional simple code below to get you started. You can add error checking, max size stuff etc after you get something simple working.
The $_FILES array is a 3 dimensional array built into PHP, and that's where all the uploaded file info is stored.
There will only be ONE element for each 'name=' part of the HTML INPUT tag.
So if your INPUT tag looks like this:
<INPUT name="InpFile[]" type="file" />
The $_FILES array will have one top array element named 'InpFile'.
Also notice the [] after the InpFile.....that tells PHP that each time you use an input tag with that same 'name' it will add it to that same $_FILES array top element.
Within that one element there are 5 other array elements with the names: 'name', 'type', 'tmp_name', 'error', and 'size'.
And each one of those array elements will contain the data for each file that is uploaded.
Your first uploaded file name will be in $_FILES ['InpFile']['name']['0']
And the other info about your first uploaded file will also be in the array the same way, for example the size of the first file will be in $_FILES ['InpFile']['size']['0']
Each subsequent file name will be in $_FILES ['InpFile']['name'][1], $_FILES ['InpFile']['name'][2]....etc
After your upload, each file will have a random temporary name in the $_FILES ['InpFile']['tmp_name'][0...n] element, which is the name that it uses to first upload the files to a temporary area.
SO, after you upload, you have to move the files from the temporary area to where you want them.
That is done with this statement:
move_uploaded_file($_FILES['InpFile']['tmp_name'][$Key],
$_FILES['InpFile']['name'][$Key] )
or die("Move from Temp area failed");
In the foreach statement below, $Key and $Name are only there so that $Key will get assigned increasing numbers for each iteration...i.e. 0, 1, 2.....etc, and that you can then use $Key to reference the name, tmp_name, etc of each file in the array.
This code lets you do it all on one page, since the form actually calls itself (action="") to post. So the first time the page is loaded, you would get an error in the php code because $_FILES hasn't been set yet......so all the code is in an If statement: If ($_FILES).
After you submit the form, it will do it's thing and then echo a status for each file after it's been moved to your area.
Also, this code will upload the file to the same directory the page is in...you can change all that using info from other posts on SO.
<FORM action="" method="post" enctype="multipart/form-data">
<P align="center"><B>Choose Files</B><BR>
<BR>
File One:
<INPUT name="InpFile[]" type="file" />
<BR>
<BR>
File Two:
<INPUT name="InpFile[]" type="file" />
<BR>
</P>
<P align="center"><BR>
<INPUT type="submit" name="submit" value="UpLoad">
</P>
</FORM>
<H3 align="center"> </H3>
<H3 align="center">Status:</H3>
<P align="center"> </P>
<P align="center">
Put this PHP Code right here on the same page:
<?php
If ($_FILES) {
foreach ($_FILES ['InpFile']['name'] as $Key => $Name) {
move_uploaded_file(
$_FILES['InpFile']['tmp_name'][$Key],
$_FILES['InpFile']['name'][$Key]
) or die("Move from Temp area Failed");
$EFileName = $_FILES['InpFile']['name'][$Key];
echo "<P>$EFileName: Uploaded";
}
}
?>

You need to change the value of the name attribute in the HTML side to file[] and then in PHP just iterate through $_FILES['files'] and process each element as you normally would with a single file.

Related

Uploading file from form with PHP

So, I used a form to upload files to a directory.
The PHP code is as follows:
if(isset($_POST["submit"]))
{
move_uploaded_file($_FILES['cvfile1']['tmp_name'], '/uploads/'.$oor1 . '_CV_' . $firstname . '_' . $lastname);
}
But when I execute it, it seems to not place the file anywhere. I have been refreshing the uploads directory for a while, hoping it would show up.
The variables have been declared and pulled off from the form
You can use multiple file upload
<input type="file" name="img" multiple>
OR
<input name="userfile[]" type="file" /><br />
<input name="userfile[]" type="file" /><br />

Appending Data to Uploaded File Using PHP

I'm making a PHP upload form, but need to add some additional data to each image based on what the user types in. For example, they choose the file to upload and type in the name, height, width, and price of that file, then hit submit. That information needs to be stored with the photo or appended to the metadata.
Here's what I have for submitFile.php:
<form enctype="multipart/form-data" action="Upload.php"
method="post">
<input type="hidden" name="MAX_FILE_SIZE" value="100000000" />
Select a File: <input name="uploaded_file" type="file" /><br/>
<input type="submit" value="Upload" />
And here's what I have for Upload.php:
<?php
$uploaddir = "uploads/images";
$uploadfile = $uploaddir.basename($_FILES['uploaded_file']['name']);
echo "<pre style= font-size:20px>";
if (move_uploaded_file($_FILES['uploaded_file']['tmp_name'],$uploadfile))
{
echo "<b>File has been successfully uploaded!</b>.\n";
}
else{
echo "<b>File upload failed!</b>.\n";
}
echo '<br/>Here is some more debugging info:'."<br/>";
echo "Name:".$_FILES["uploaded_file"]["name"]."<br/>";
echo "File Type:".$_FILES["uploaded_file"]["type"]."<br/>";
echo "File Size:".($_FILES["uploaded_file"]["size"]/1024)." Kb<br/>";
echo "Temp File:".$_FILES["uploaded_file"]["tmp_name"]."<br/>";
echo "</pre>";
?>
</form>
For JPEGs (and maybe TIFFs?), you should use something like this.
However, for PNGs, checkout this answer.

html form send data of upload file to php page, I want to handle it on php page

HTML code is below
Upload Your pic only in jpg (Less 1 MB)
<input type="file" title="Upload Your pic in jpg (Less 1 MB)" accept="image/jpeg" required="" class="select-style" tabindex="1" name="file[]" multiple />
PHP code is below:
echo $_POST[$_FILES['file[]']];
echo $_POST[$_FILES["file"]["size"]];
Your fomr must contain
enctype="multipart/form-data"
Like :-
<form name="upload" id="upload" method="post" action="" enctype="multipart/form-data">
You can use $_FILES['file']['size'][0]; to get size of uploaded file
Hope this will help you
Thanks
Ok..
here is my HTML Page page name stack.html
<form name="upload" id="upload" method="post" action="stack.php" enctype="multipart/form-data">
<input type="file" title="Upload Your pic in jpg (Less 1 MB)" accept="image/jpeg" required="" class="select-style" tabindex="1" name="file[]" multiple />
<input type="submit" value="submit">
</form>
and here my PHP page page name stack.php
<?php
if(!empty($_FILES)){
echo "<pre>";
print_r($_FILES);
echo "</pre>";
exit;
}
?>
See if it gives any luck. Try it in php file..
foreach($_FILES as $file){
print_r($file['size']);
print_r($file['name']);
//if you want total size of all images
echo array_sum($file['size']);
//if you want individual name
for($i=0;$i<count($file['name']);$i++){
echo $file['name'][$i];
echo $file['size'][$i];
}
}

Adding file name to database without uploading it

I'm making a system for adding files to a database. I use a form:
<form action="insert.php" method="post" enctype="multipart/form-data">
Fil: <input type="file" name="file" id="file">
Titel: <input type="text" name="titel" /><br />
Längd (min): <input type="text" name="langd" /><br />
Medverkande: <input type="text" name="medverkande" /><br />
Reporter: <input type="text" name="reporter" /><br />
Fotograf: <input type="text" name="fotograf" /><br />
Sökord: <input type="text" name="sokord" /><br />
<input type="submit" />
</form>
The code in insert.php:
<?php
$con = mysql_connect("database","user","password");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("165666-kltvplay", $con);
$filnamn = $_FILES["file"]["name"] ;
$sql="INSERT INTO Blad1 (ProgramID, Titel, Langd, Medverkande, Reporter, Fotograf, Sokord)
VALUES
('$filnamn','$_POST[titel]','$_POST[langd]','$_POST[medverkande]','$_POST[reporter]','$_POST[fotograf]','$_POST[sokord]')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "En ny film inlagd: <br> ";
echo $filnamn;
mysql_close($con);
?>
But when I add the file it seems to be uploading the whole file because there is a % counter in my browser and it's taking a loooong time to complete(the files are qute big). I just want the name of the file inserted into the database (and that is working) but not to upload the whole file.
And is it possible to add just the name and not the file exetension?
You'll have to do some JavaScript magic. Once the user has selected a file, you can read the file name:
var fileName = document.getElementById('file').value;
Then put that value into a hidden input field (that is inside your form):
document.getElementById('hidden-filename').value = fileName;
Then hook into the form's submit event and remove the file input so it won`t get submitted.
On the server you read the value of the hidden-filename (or whatever the name) and insert it into the DB.
Be warned though that not all browsers will return the actual file path. The name of the file will be correct, but the path may not be.
Also note that you won't be able to do anything with this file then (on the server or on the client).
AS for the last question you had (no extension), look at this: PHP, get file name without file extension

upload multiple photos

I have a form which I am using to upload users photos but the problem is that I can upload 1 photos each time .like facebook I want my users to select multiple images in one shot. can anyone please guide. here is my present code.
<tr><td><input type="file" name="photos[]" /></td><td><input type="text" size="35" name="descriptions[]" /></td></tr>
and php is processing the uploaded images. can you please tell how should I do so that multiple images can be selected and uploaded in one shot
first thing is you need to make your form multipart
<form method="post" action="where_ever" enctype="multipart/form-data">
And if you use HTML5 the next part is to create a named array
<input type="file" accept='image/*' name="multiImageUpload[]" id="multiImageUpload" />
<input type="file" accept='image/*' name="multiImageUpload[]" id="multiImageUpload" />
<input type="file" accept='image/*' name="multiImageUpload[]" id="multiImageUpload" />
This will put all files into a $_POST array called multiImageUpload.
In order to allow a name to accept multiples in an array you need to use []
at the back of name, name[] or images[] or files[], also using the HTML5
property multiple multiple='' or multiple='multiple' will allow you
to select multiple files at once form a single input.
Here's some working sample code to play around with
The HTML
<form method="post" action="upload.php" enctype="multipart/form-data">
<input name='uploads[]' type="file" multiple=""/>
<input type="submit" value="Send">
</form>
The PHP
foreach ($_FILES['uploads']['name'] as $filename) {
echo '<li>' . $filename . '</li>';
}
// full contents of $_FILS
echo '<pre>';
var_export($_FILES);
echo '</pre>';

Categories