Uploading multiple images with one input field - php

i have created a photography website with an admin page that uploads photos to different categories in a mysql table. This much works, but i can only upload one file at a time and i'd like to be able to select multiple images.
Here's the form
<form action="index.php" enctype="multipart/form-data" name="myForm" id="myForm" method="post">
<select name="category" id="category">
<option value="Nature">Nature</option>
<option value="People">People</option>
<option value="Abstract">Abstract</option>
</select>
<input type="file" name="fileField" id="fileField" />
<input type="submit" name="submit" id="submit" value="Add Images" />
</form>
And here's the php for parsing the form
if (isset($_POST['submit'])) {
$category = mysql_real_escape_string($_POST['category']);
// Add this product into the database now
$sql = mysql_query("INSERT INTO images (category, date_added)
VALUES('$category',now())") or die (mysql_error());
$pid = mysql_insert_id();
// Place image in the folder
$newname = "$pid.jpg";
move_uploaded_file( $_FILES['fileField']['tmp_name'], "../photos/$newname");
header("location: thumbnail_generator.php");
exit();
}
I looked into the html5 file input method, and as far as i can tell, i can change the input as folllows:
<input type="file" name="fileField[]" id="fileField" multiple="multiple"/>
This allows me to select multiple files on the site, but i can't figure out how to implement this into my php. Any help would be much appreciated.

<form method="post" action="" enctype="multipart/form-data">
<input type="hidden" name="MAX_FILE_SIZE" value="500000">
Add Photos <input multiple="true" onchange="this.form.submit()" type="file" name="photos[]"/>
<input type="hidden" name="sendfiles" value="Send Files" />
</form>
<?php
define ("MAX_SIZE","5000");
function getExtension($str)
{
$i = strrpos($str,".");
if (!$i) { return ""; }
$l = strlen($str) - $i;
$ext = substr($str,$i+1,$l);
return $ext;
}
$errors=0;
if(isset($_POST['sendfiles']))
{
$uploaddir = "files/"; //a directory inside
foreach ($_FILES['photos']['name'] as $name => $value)
{
$filename = stripslashes($_FILES['photos']['name'][$name]);
//get the extension of the file in a lower case format
$extension = getExtension($filename);
$extension = strtolower($extension);
echo "\n This is the extension: ",$extension;
if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "png") && ($extension != "gif"))
{
//print error message
?>
<h4>Unknown extension!</h4>
<?php
$errors=1;
}
else
{
$size=filesize($_FILES['photos']['tmp_name'][$name]);
if ($size > MAX_SIZE*1024)
{
?>
<h4>You have exceeded the size limit!</h4>
<?php
$errors=1;
}
$image_name=$filename.'.'.$extension;
$newname="files/".$image_name;
$copied = copy($_FILES['photos']['tmp_name'][$name], $newname);
if (!$copied)
{
?>
<h4>Copy unsuccessfull!</h4>
<?php
$errors=1;
}
}
}
//echo "Images uploaded successfully";
}
//mysql_close($dbhandle);
?>

You are probably looking for something like uploadify or swfupload or plupload.

It works as-if there were multiple file fieldsĀ­Docs, it's transparent to PHP. Here is some simple example code:
<html>
<body>
<form action="" method="post" enctype="multipart/form-data">
<input type="file" name="fileField[]" id="fileField" multiple="multiple">
<input type="text" name="test" value="test">
<input type="submit" name="submit">
</form>
</body>
</html>
<?php
var_dump($_FILES, $_POST);
Store it on your host and request it. You can then play around with it, it will show you the structure of the $_FILES and $_POST array.
Example output:
array
'fileField' =>
array
'name' =>
array
0 => string 'hakre-iterator-fun-cut-top.png' (length=30)
1 => string 'hakre-iterator-fun-cut-middle.png' (length=33)
'type' =>
array
0 => string 'image/png' (length=9)
1 => string 'image/png' (length=9)
'tmp_name' =>
array
0 => string '/tmp/php1A2.tmp' (length=15)
1 => string '/tmp/php1A3.tmp' (length=15)
'error' =>
array
0 => int 0
1 => int 0
'size' =>
array
0 => int 234001
1 => int 213058
array
'test' => string 'test' (length=4)
'submit' => string 'Submit' (length=6)
See Uploading multiple filesĀ­Docs.

Simple! Just Add multiple="true" to your input tag.
<input name "example" type="file" multiple="true"/>

Try out this.
http://www.uploadify.com/demos/
Uploadify is a powerful and highly-customizable file upload script. Uploadify is easy to get up and running with
minimal effort and little coding knowledge.

you will receive an array of images -> fileField[]. Just iterate through this array and add the images the same way you were adding them before. Also, I'd suggest using this, very nice script - http://valums.com/ajax-upload/
EDIT: Just don't forget to implement at least some security checks, like min and max upload size, file extensions and mime-type checking! Even if it's for the back-end, this could still lead to unpleasant events.

Wouldn't something like creating an array work too? So what he could do is
$images = array();
Then in his form just add a add to image list button? From there he just keep adding as many images as he wants and then just iterate over the array and add to the database?

Related

Uploading multiple images to server and database using PHP and a single HTML input [duplicate]

This question already has answers here:
Multiple file upload in php
(14 answers)
Closed 1 year ago.
Could someone please assist as I would like to upload multiple images to the server as well the image names to the database.
The below code works for uploading the images to the server:
View:
<form action="<?php echo URLROOT; ?>/posts/add" method="post" enctype='multipart/form-data'>
<input type="file" name="file[]" multiple>
<input type="submit" name=submit value="Submit">
</form>
Controller:
if($_SERVER['REQUEST_METHOD'] == 'POST'){
// Count total files
$countfiles = count($_FILES['file']['name']);
// Looping all files
for($i=0;$i<$countfiles;$i++){
$filename = $_FILES['file']['name'][$i];
// Upload file
move_uploaded_file($_FILES['file']['tmp_name'][$i], dirname(__DIR__)."/img/".$filename);
}
} else {
// Load view with errors
$this->view('posts/add');
}
}
I am also able to upload the 3 image names when using the below code with 3 separate inputs:
View:
<form action="<?php echo URLROOT; ?>/posts/add" method="post">
<input type="file" name="image1">
<input type="file" name="image2">
<input type="file" name="image3">
<input type="submit" name=submit value="Submit">
</form>
Controller:
if($_SERVER['REQUEST_METHOD'] == 'POST'){
// Sanitize POST array
$_POST = filter_input_array(INPUT_POST, FILTER_SANITIZE_STRING);
$data = [
'user_id' => $_SESSION['user_id'],
'image1' => trim($_POST['image1']),
'image2' => trim($_POST['image2']),
'image3' => trim($_POST['image3']),
];
// Validated
if($this->postModel->addPost($data)){
flash('post_message', 'Post Added');
redirect('posts');
} else {
die('Something went wrong');
}
} else {
$data = [
'image1' => '',
'image2' => '',
'image3' => ''
];
$this->view('posts/add', $data);
}
}
Could someone please advise on how I could combine the code, in order to use a single file input for uploading the images to server, as well as the image names to the database?
Complete Code
<form method='post' action='' enctype='multipart/form-data'>
<input type="file" name="file[]" id="file" multiple>
<input type='submit' name='submit' value='Upload'>
</form>
PHP
<?php
if(isset($_POST['submit'])){
$imageName =$_FILES['file']['name'];
// Count total files
$countfiles = count($_FILES['file']['name']);
// Looping all files
for($i=0;$i<$countfiles;$i++){
$filename = $_FILES['file']['name'][$i];
// Upload file
move_uploaded_file($_FILES['file']['tmp_name'][$i],'upload/'.$filename);
//insert code
$query = "insert into images(images) values('".$imageName."')";
mysqli_query($con,$query);
}
}
?>
Use this input code -
<input type="file" name="image[]" id="file" multiple>
And count file in php file then use loop for iterating file like-
$counts = count($_FILES['image']['name']);
for($i=0;$i<$counts;$i++){
//uploading code here
}

Submitting Image From Form Apparently Wrong Octet

A simple form with an image viewer below it in the same test.php script, the image gives errors in displaying. Disabling the headers and viewing the image data on the screen, it seems to have many of the little black ? diamonds all over it so probably somehow the wrong octet is being submitted. Where does the encoding get lost and how do I fix it?
To clarify, I am not trying to upload and save the file anywhere and I am not trying to insert it into a database. I simply want the data stream to directly display itself on the screen.
Also, the conditional around the PHP code is simply so that it does nothing until it receives a file. No validation needed as this is used only locally on my development system as a test tool.
test.php
<form method="POST" action="test.php" enctype="multipart/form-data">
<fieldset>
<legend>Image Functions Tester</legend>
<p><label for="image">Image</label>
<input type="file" name="fileToProcess" id="fileToProcess">
<p><input name="insert" type="submit" value="Upload">
</fieldset>
</form>
<?php
if (isset($_FILES['fileToProcess'])) :
$file = $_FILES['fileToProcess'];
$image = file_get_contents($file['tmp_name']);
// TEST ConvertImage() FUNCTON HERE
// Get the image mime type
$mimetype = Array("1" => "image/gif",
"2" => "image/jpeg",
"3" => "image/png",
"6" => "image/bmp");
// Add headers and output the image
Header("Pragma: no-cache");
Header('Content-type: ' . $mimetype[exif_imagetype($image)]);
echo $image;
endif;
?>
I guess you are trying to display uploaded image. in your code I see that you are trying to validate to ensure that user submit only images. In php they are just two best method to ensure that submitted files are not virus but image
1.) using Getimagesize Function
2.) Fileinfo method.
I have implemented the validation in your code to ensure workability.
First create a directory call uploads where files will be uploaded and run this your update code
<form method="POST" action="test.php" enctype="multipart/form-data">
<fieldset>
<legend>Image Functions Tester</legend>
<p><label for="image">Image</label>
<input type="file" name="fileToProcess" id="fileToProcess">
<p><div class="ButtonCenter">
<input name="insert" type="submit" value="Upload">
</div>
</fieldset>
</form>
test.php
<?php
if (isset($_FILES['fileToProcess'])) {
$uploadDir = "uploads/";
$filename= $_FILES['fileToProcess']['name'];
$file_types=array(
'image/gif',
'image/jpeg',
'image/png',
'image/jpg',
'image/GIF',
'image/JPEG',
'image/PNG',
'image/JPG'
);
// validate image using getimagesize function
$image_info =getimagesize($_FILES['fileToProcess']['tmp_name']);
//print_r($image_info);
$mime_image = $image_info['mime'];
// ensure the file is image via getimagesize function
if ( ! ( in_array($mime_image, $file_types) ) ) {
echo "you can only upload images";
exit();
}
//validate image using file info function
$f = finfo_open(FILEINFO_MIME_TYPE);
$mime = finfo_file($f, $_FILES['fileToProcess']['tmp_name']);
if ( ! ( in_array($mime, $file_types) ) ) {
echo "You can only upload Images";
exit();
}
finfo_close($f);
if(move_uploaded_file($_FILES['fileToProcess']['tmp_name'],"$uploadDir/".$filename)) {
echo "File uploaded successfully";
echo "<img src='uploads/$filename' width='100px' height='100px'>";
}
}
?>
After fighting with this for two days, I just found the problem although I don't fully understand the reason it makes a difference. Apparently the form and the viewer cannot be on the same page so splitting them into two files works perfectly:
test.php
<?php
if (!isset($_FILES['fileToProcess'])) : ?>
<div class="PageCaption">Site Administration<hr></div>
<form method="POST" action="testviewer.php" enctype="multipart/form-data">
<fieldset>
<legend>Image Functions Tester</legend>
<p><label for="image">Image</label>
<input type="file" name="fileToProcess" id="fileToProcess">
<p><div class="ButtonCenter">
<input name="insert" type="submit" value="Upload">
</div>
</fieldset>
</form><?php
endif; ?>
testviewer.php
<?php
if (isset($_FILES['fileToProcess'])) :
$file = $_FILES['fileToProcess'];
$image = file_get_contents($file['tmp_name']);
// Get the image mime type
$mimetype = Array("1" => "image/gif",
"2" => "image/jpeg",
"3" => "image/png",
"6" => "image/bmp");
// Add headers and output the image
Header("Pragma: no-cache");
Header('Content-type: ' . $mimetype[exif_imagetype($image)]);
echo $image;
endif;?>

How to upload multiple files one by one

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

PHP - prevent html5 input type file attribute multiple hack?

Hello I'm doing form upload 4 files field. Each field can upload 1 file.
but I just know that hacker can hack with firebug to add html5 "multiple" attribute.(see the screenshot)
and then hacker can upload exceed 4 files now that I don't want to happen.
Question : How can I do to limit the upload file to 4 files?
here is my current code
for($i=0;$i<count($_FILES["file"]["name"]);$i++) {
if($_FILES["file"]["name"][$i] != "") {
$split = explode('.', $_FILES["file"]["name"][$i]);
$ext = end($split);
$tempFile = $_FILES['file']['tmp_name'][$i]; //3
$targetFile = "upload/". date('Y-m-d')."_".($i+1).".".$ext; //5
move_uploaded_file($tempFile,$targetFile); //6
}
}
..
<form method="post" action="upload.php" enctype="multipart/form-data">
<input type="file" name="file[]"/><br>
<input type="file" name="file[]"/><br>
<input type="file" name="file[]"/><br>
<input type="file" name="file[]"/><br><br>
<input type="submit" value="Upload"/>
</form>
Things like this must be validated server-side.
if(count($_FILES["file"]["name"]) > 4) {
// show the user an error and refuse to continue
}

Issue with uploading multiple files on a single html page using php

I am trying to build a web page where users can edit images portrayed on their public pages. There are 3 images that display on their public page and I've set up 3 HTML forms in order to handle the 3 separate files.
I only have 1 listed below because once I figure out the fix to 1 I'll be able to duplicate the fix to the other 2,
I have other upload pages on my website and they work fine, but for some reason this page is giving me trouble. I can select a file but when I want to upload it my php code doesn't read that there is anything being posted.
*I've commented out the function call (I know it works) I just need to know why my php code won't read that there is a file there.
If I had to guess it'd be something with how it's named or how it's being tossed to the php code.
The code looks like this:
<div class="academic" style="width:250px;">
<br>
<?php
if(isset($_FILES['aca']) === true)
{
echo 'please print'; //It doesn't
if(empty($_FILES['aca']['name']) === true)
{
echo 'Please choose a file! <br>';
}
else
{
$allowed = array('jpg', 'jpeg', 'gif', 'png');
$file_name = $_FILES['aca']['name'];
$file_extn = strtolower(end(explode('.', $file_name)));
$file_temp = $_FILES['aca']['tmp_name'];
echo '<br>';
echo '<br>';
print_r($_FILES['aca']['tmp_name']);
echo '<br>';
echo '<br>';
if(in_array($file_extn, $allowed) === true) {
//upload_image($file_temp,$file_extn);
echo 'You have uploaded a picture!';
echo '<b><h3>Press submit again to finish the upload</h3></b>';
//echo "<script>window.top.location='../hidden/viewPNM.php?id=$permi'</script>";
}
else
{
echo 'Incorrect File Type!! <br> Allowed: ';
echo implode(', ', $allowed);
}
}
}
?>
<form action="" method="post" enctype="multipart/form-data">
<input type="file" name="aca" id="aca">
<input type="submit" value="Upload">
</form>
</div>
</span>
Okay...here is what you can try to do:
Move the whole PHP code UNDER the form code. I remember that sometimes wierd bugs with that were happening, and the code didnt run
If that doesnt work, do following:
Change <input type="file" name="aca" id="aca"> to <input multiple="true" type="file" name="aca[]" />
Add this code above the submit button: <input type="hidden" name="sendfiles" value="Send Files" />
Replace if(isset($_FILES['aca']) === true) with if(isset($_POST['sendfiles']))
If this doesn't work, I can offer you a way to allow multiple files being uploaded from one button. (Took the code from my website I made before)

Categories