PHP Multiple File Array - php

I have the following code which works and uploads but it will not cycle through the array to upload every file, just the first file.
<form method="post" enctype="multipart/form-data" action="http://<?php echo $pageURL;?>">
<input class="new" multiple="multiple" name="documents[]" type="file" />
<input class="new" multiple="multiple" name="documents[]" type="file" />
<input type="submit" class="button" name="addMaterials" value="Add" />
<?php
foreach($_FILES['documents']['tmp_name'] as $key => $tmp_name)
{
$file_name = $key.$_FILES['documents']['name'][$key];
$file_size =$_FILES['documents']['size'][$key];
$file_tmp =$_FILES['documents']['tmp_name'][$key];
$file_type=$_FILES['documents']['type'][$key];
move_uploaded_file($file_tmp,"files/".time().$file_name);
}
?>
I need it to cycle through my documents[] file array.
Example print_r() of the documents array:
Array (
[name] => Array ( [0] => AcroRd32.exe )
[type] => Array ( [0] => application/x-msdownload )
[tmp_name] => Array ( [0] => C:\xampp\tmp\phpE8BD.tmp )
[error] => Array ( [0] => 0 )
[size] => Array ( [0] => 1343112 )
)
Any help appreciated.

you can use my updated code and as per my demo it is working perfect for multiple file upload
<?php
if(isset($_FILES['documents'])){
foreach($_FILES['documents']['tmp_name'] as $key => $tmp_name)
{
$file_name = $key.$_FILES['documents']['name'][$key];
$file_size =$_FILES['documents']['size'][$key];
$file_tmp =$_FILES['documents']['tmp_name'][$key];
$file_type=$_FILES['documents']['type'][$key];
move_uploaded_file($file_tmp,"galleries/".time().$file_name);
}
}else{
echo "<form enctype='multipart/form-data' action='test1.php' method='POST'>";
echo "File:<input name='documents[]' multiple='multiple' type='file'/><input type='submit' value='Upload'/>";
echo "</form>";
}
?>

For anyone trying to do it with a single file php function (i`m using classes, but you can change to a function):
html:
<input type="file" name="foto[]" />
<input type="file" name="foto[]" />
<input type="file" name="foto[]" />
<input type="file" name="foto[]" />
<input type="file" name="foto[]" />
php:
if (isset($_FILES['foto'])) {
$arquivo = array();
foreach ($_FILES['foto']["name"] as $file=>$key) {
// the empty input files create an array index too, so we need to
// check if the name exits. It means the file exists.
if (!empty($_FILES['foto']["name"][$file])) {
$arquivo ["name"] = $_FILES['foto']["name"][$file];
$arquivo ["type"] = $_FILES['foto']["type"][$file];
$arquivo ["tmp_name"] = $_FILES['foto']["tmp_name"][$file];
$arquivo ["error"] = $_FILES['foto']["error"][$file];
$arquivo ["size"] = $_FILES['foto']["size"][$file];
$foto = new foto(); // create an obj foto
// $arquivo means file, it`s our file format as a single $_file['file']
if ($foto -> upload($arquivo)) { // if its uploaded than save
$foto -> save();
}
}
}
}
on my foto class:
public function upload($foto) {
$upload_dir = "D:/xampp/htdocs/prova/fotos/";
$file_dir = $upload_dir . $foto["name"];
$move = move_uploaded_file($foto["tmp_name"], $file_dir);
$this -> arquivo = $foto["name"]; // use this to save to db later
// this serves to return true if the file is uploaded
$retorno = ($move) ? 1 : 0;
return $retorno;
}

Try with this code for multifile upload
<form method="post" action="upload-page.php" enctype="multipart/form-data">
<input name="filesToUpload[]" id="filesToUpload" type="file" multiple="" />
</form>
In PHP
if(count($_FILES['uploads']['filesToUpload'])) {
foreach ($_FILES['uploads']['filesToUpload'] as $file) {
//do your upload stuff here
echo $file;
}
}
To show the file name using javascript
//get the input and UL list
var input = document.getElementById('filesToUpload');
var list = document.getElementById('fileList');
//empty list for now...
while (list.hasChildNodes()) {
list.removeChild(ul.firstChild);
}
//for every file...
for (var x = 0; x < input.files.length; x++) {
//add to list
var li = document.createElement('li');
li.innerHTML = 'File ' + (x + 1) + ': ' + input.files[x].name;
list.append(li);
}

it's easy to upload multiple files, follow these steps.
use array notation means square brackets with the name of the input like this
<input type="file" id="indtbl_logo[]" name="indtbl_logo[]" multiple />
you can loop throught this using $_FILES Global Variable
foreach ($_FILES['indtbl_logo']['tmp_name'] as $key => $tmp_name) {
$file_name = $key . $_FILES['indtbl_logo']['name'][$key];
$file_size = $_FILES['indtbl_logo']['size'][$key];
$file_tmp = $_FILES['indtbl_logo']['tmp_name'][$key];
$file_type = $_FILES['indtbl_logo']['type'][$key];
echo $file_name;
echo "<br>";
}

Try this way of loop your documents array()
<?php
foreach($_FILES['documents']['tmp_name'] as $key => $tmpName) {
$file_name = $_FILES['documents']['name'][$key];
$file_type = $_FILES['documents']['type'][$key];
$file_size = $_FILES['documents']['size'][$key];
$file_tmp = $_FILES['documents']['tmp_name'][$key];
move_uploaded_file($file_tmp,"files/".time().$file_name);
}
?>

File upload using multiple input fields.
HTML
<form action="" method="post" enctype="multipart/form-data">
<p><input type="file" name="file_array[]"></p>
<p><input type="file" name="file_array[]"></p>
<p><input type="file" name="file_array[]"></p>
<input type="submit" value="Upload all files">
</form>
PHP
<?php
if(isset($_FILES['file_array'])){
$name_array = $_FILES['file_array']['name'];
$tmp_name_array = $_FILES['file_array']['tmp_name'];
$type_array = $_FILES['file_array']['type'];
$size_array = $_FILES['file_array']['size'];
$error_array = $_FILES['file_array']['error'];
for($i = 0; $i < count($tmp_name_array); $i++){
if(move_uploaded_file($tmp_name_array[$i], "test_uploads/".$name_array[$i])){
echo $name_array[$i]." upload is complete<br>";
} else {
echo "move_uploaded_file function failed for ".$name_array[$i]."<br>";
}
}
}
?>

Related

Multiple File Upload doesn't Insert all Files in Database

I have a Problem with Insert in Database. It Insert only the first Uploaded Image :/ Here is my PHP Code:
function reArrayFiles(&$file_post) {
$file_ary = array();
$file_count = count($file_post['name']);
$file_keys = array_keys($file_post);
for ($i=0; $i<$file_count; $i++) {
foreach ($file_keys as $key) {
$file_ary[$i][$key] = $file_post[$key][$i];
}
}
return $file_ary;
}
$file_ary = reArrayFiles($_FILES['files']);
$allowedTypes = array(IMAGETYPE_PNG, IMAGETYPE_JPEG, IMAGETYPE_GIF);
foreach($file_ary as $key => $file){
static $i = 1;
if($file['error'] == 4){
continue;
}elseif(!in_array(exif_imagetype($file['tmp_name']), $allowedTypes)){
$error = '<span style="color:red">Filename '.$file['name'].' <b>type</b> is not allowed.</span><br>';
}elseif($file['size'] > 2097152){
$error = '<span style="color:red">Filename '.$file['name'].' exceeds maximum allowed <b>size</b></span>.<br>';
}else{
$getfilename= $file["name"];
$FileName="U[$user->id].$getfilename";
$time = time();
$output_dir = "uploads/";
if(!file_exists("uploads/".$FileName)){
move_uploaded_file($file["tmp_name"], "uploads/".$FileName);
}else{
$FileName="$time.$getfilename";
move_uploaded_file($file["tmp_name"], "uploads/".$FileName);
}
mysql_query("INSERT INTO ads_pictures (path, filename, timestamp) VALUES('".$output_dir."', '".$FileName."', '".$time."')");
}
$i++;
}
And this is the HTML Code:
<form method="post" enctype="multipart/form-data" action="">
<input id="image" type="file" name="files[]" accept="image/*">
<input id="image" type="file" name="files[]" accept="image/*">
<input id="image" type="file" name="files[]" accept="image/*">
<input id="image" type="file" name="files[]" accept="image/*">
<input name="submit" class="btn submit" value="Upload" type="submit">
</form>
It Should normally Insert all Uploaded Files to Database but Unfortanetly it insert only the First selected file. Thank you for Help.
Have you considered replacing this:
foreach($file_ary as $key => $file){
static $i = 1;
with this:
$i = 1;
foreach($file_ary as $key => $file){
?
let us know if that helped.

Upload two different files in the same form

The issue here is, when I Upload videos, it works perfectly but not images which is giving me a hard time to figure out what the error may be
This is what the HTML looks like:
<form action="index.php" method="post" enctype="multipart/form-data" >
<h1>Browse for file to upload:</h1>
</div>
<div>
<label for="file"><h1><b>Select Video</b></h1></label>
<input type="file" name="fileToUpload1[]" id="fileToUpload" >
<br><br>
<label for="file"><h2><b>Select Image</b></h2></label>
<input type="file" name="fileToUpload1[]" id="fileToUpload" >
<br><br>
<input type="submit" value="Upload" name="submit">
</form>
The PHP Script looks like this:
$error = null;
$success = null;
$info = [];
$uploadOk = 1;
$allowedMimes = ['video/mp4', 'image/jpg'];
if(isset($_POST["submit"])) {
$counter = 0;
foreach ( $_FILES['fileToUpload1']['name'] as $file ):
$target_file = UPLOAD_DIR . basename($file);
if ( in_array(mime_content_type($_FILES['fileToUpload1']["tmp_name"][$counter]), $allowedMimes) ){
if (move_uploaded_file($_FILES['fileToUpload1']["tmp_name"][$counter], $target_file)) {
$info[] = "File ".++$counter."($file) uploaded successfully";
}else {
$info[] = "File ".++$counter."($file) cannot be uploaded";
}
} else {
$info[] = "File ".++$counter. " is not allowed.";
}
endforeach;
} else {
echo "upload a file.";
}
?>
<ul>
<?php foreach($info as $i){ ?>
<li><?=$i;?></li>
<?php }?>
</ul>
<? } ?>
The mimetype of jpg files is actually image/jpeg (and not iamge/jpg), so if you are trying to upload jpg files you should change your $allowedMimes variable to:
$allowedMimes = ['video/mp4', 'image/jpeg'];
Also - if you want to support other image types you can use:
$allowedMimes = ['video/mp4', 'image/png', 'image/jpeg', 'image/gif', 'image/bmp'];
Another option - if you want to support all image/audio/video types you can check only the first part of the string:
$allowedTypes = ['video', 'image', 'audio'];
...
if ( in_array(
array_shift(
explode("/",
mime_content_type($_FILES['fileToUpload1']["tmp_name"][$counter])
)
),
$allowedTypes) )
If you are using php>=5.4 you can use:
$allowedTypes = ['video', 'image', 'audio'];
...
if ( in_array(
explode("/",
mime_content_type($_FILES['fileToUpload1']["tmp_name"][$counter])
)[0],
$allowedTypes) )

Upload multiple images to Database MYSQLI

I am planning to have a web gallery. However, it is hard for me to use PHP to insert DB. The following code:
HTML -- I want to make a form which has category and multiple images that can be inserted into DB at the same time.
<form action="upload" method="POST" enctype="multipart/form-data">
<p> Upload : <input type="file" id="file" name="images" /> </p>
<p> Category : <input type="text" name="imageCategory"> </p>
<p> <input type="submit" name="submit" value="Upload!" /> </p>
</form>
DATABASE
I am using imageName as VARCHAR not BLOB TYPE.
PHP
<?php
include ("dbConnect.php");
if(isset($_POST["submit"])) {
$image = $_POST['images']['tmp_name'];
$imageName = $_POST['images']['name'];
$imageSize = $_POST['images']['size'];
$imageType = $_POST['images']['type'];
$imageCategory = $_POST['imageCategory'];
$result = $mysqli->query("INSERT INTO imageTable (imageName, imageCategory, imageSize, imageType)
VALUES ('$imageName', '$imageCategory', '$imageSize' , '$imageType' );")
or die(mysqli_error($mysqli));
} else {
echo "<p> It is not working </p>";
}
header("location: index");
$mysqli->close();
?>
The problem is, the category is the only one has inserted into the database successfully. But not with the imageName, imageType, and imageSize. And also i want the image to be stored into database so that I can retrieve the image from DB on the other web page. Any ideas?
You can use 'multiple' property in the 'input' tag like this :
<form action="file-upload.php" method="post" enctype="multipart/form-data">
Send these files:<br />
<p> <input name="userfile[]" type="file" multiple='multiple' /> </p>
<p> Category : <input type="text" name="imageCategory"> </p>
<input type="submit" value="Send files" />
</form>
User can select multiple files and upload them.
And at the server you will do this :
if (isset($_FILES["userfile"]) && !empty($_FILES["userfile"])) {
$image = $_FILES['userfile']['tmp_name'];
$imageName = $_FILES['userfile']['name'];
$imageSize = $_FILES['userfile']['size'];
$imageType = $_FILES['userfile']['type'];
$imageCategory = $_POST['imageCategory'];
$len = count($image);
$path = "images/";
for ($i = 0; $i < $len; $i++) {
if (isset($imageName[$i]) && $imageName[$i] !== NULL) {
if(move_uploaded_file($image[$i], $path.$imageName[$i])) {
$result = $mysqli->query("INSERT INTO imageTable (imageName, imageCategory, imageSize, imageType) VALUES ('$imageName[$i]', '$imageCategory', '$imageSize[$i]' , '$imageType[$i]' )");
}
}
}
}
$mysqli->close();
header("location: index");
First off the file information won't be in the $_POST global variable it will be in the $_FILES
From http://php.net/manual/en/features.file-upload.multiple.php (modified):
Form
<form action="file-upload.php" method="post" enctype="multipart/form-data">
Send these files:<br />
<p> <input name="userfile[]" type="file" /> </p>
<p> <input name="userfile[]" type="file" /> </p>
<p> Category : <input type="text" name="imageCategory"> </p>
<input type="submit" value="Send files" />
</form>
Parse the global file variable to an array (we'll assume this is a helper function called parseFiles.php):
<?php
function reArrayFiles(&$file_post) {
$file_ary = array();
$file_count = count($file_post['name']);
$file_keys = array_keys($file_post);
for ($i=0; $i<$file_count; $i++) {
foreach ($file_keys as $key) {
$file_ary[$i][$key] = $file_post[$key][$i];
}
}
return $file_ary;
}
Move the files and insert the file information into the database :
<?php
include ("dbConnect.php");
include ("parseFiles.php");
if ($_FILES['upload']) {
$file_ary = reArrayFiles($_FILES['userfile']);
foreach ($file_ary as $file) {
$image = $file['tmp_name'];
$imageName = $file['name'];
$imageSize = $file['size'];
$imageType = $file['type'];
$imageCategory = $_POST['imageCategory'];
$result = $mysqli->query("INSERT INTO imageTable (imageName, imageCategory, imageSize, imageType)
VALUES ('$imageName', '$imageCategory', '$imageSize' , '$imageType' );")
or die(mysqli_error($mysqli));
}
} else {
echo "<p> It is not working </p>";
}
header("location: index");
$mysqli->close();
Hopefully that should do the job. I've not tested this I've just blind coded it so there may be some bugs

php multiple image upload and display each image

i'm struggle with some multiple image upload script.
what i implement to do is , upload multiple image then save each image saved path to variable
so i use later for display .
but when i run script i only can save first upload image path value.
<form action="" method="post" enctype="multipart/form-data">
<p>
<input type="file" name="pictures[]" /><br>
<input type="file" name="pictures[]" /><br>
<input type="file" name="pictures[]" /><br>
<input type="file" name="pictures[]" /><br>
<input type="submit" value="Send" />
</p>
</form>
<?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];
$ext = substr(strrchr($name, "."), 1);
$randName = md5(rand() * time());
$pathimg = "images/$randName.$ext";
move_uploaded_file($tmp_name, $pathimg );
echo '<img src="'.$pathimg.'"; >' ;
}
}
?>
this is upload path ''
for example if i upload 3 images then i want to save this 3 image uploaded path to variable each. so each variable will be $A, $B, $C
or if i upload 4 images i also want to this 4 image path to variable each then use for later
please enlighten me! thanks
Why do you expect errors while uploading.
Change
foreach ($_FILES["pictures"]["error"] as $key => $error) {
to
foreach ($_FILES["pictures"] as $key => $tempFile) {
Also, after successful upload, append the images into an array.
$arr = array();
foreach ($_FILES["pictures"] as $key => $tempFile) {
// YOUR CODE
$arr[] = '<img src="'.$pathimg.'"; >' ;
}
And print it in a loop.
if (! empty($arr)) {
foreach ($arr as $img) {
echo '<img src="'.$img.'"/>';
}
}

PHP get names of multiple uploaded files

Hi im trying to create a script to upload multiple files.
everythings works so far and all files are being uploaded.
My problem now is that i need to grap each file name of the uploaded files, so i can insert them in to a datebase.
Here is my html:
<form action="" method="post" enctype="multipart/form-data">
<input type="file" name="image[]" multiple />
<input type="submit" value="upload" />
And here is the php:
if (!empty($_FILES['image'])) {
$files = $_FILES['image'];
for($x = 0; $x < count($files['name']); $x++) {
$name = $files['name'][$x];
$tmp_name = $files['tmp_name'][$x];
$size = $files['size'][$x];
if (move_uploaded_file($tmp_name, "../folder/" .$name)) {
echo $name, ' <progress id="bar" value="100" max="100"> </progress> done <br />';
}
}
}
Really hope someone can help me with this.
/JL
You have your indexes backwards. $_FILES is an array, with an element for each uploaded file. Each of these elements is an associative array with the info for that file. So count($files['name']) should be count($files), and $files['name'][$x] should be $files[$x]['name'] (and similarly for the other attributes. You can also use a foreach loop:
foreach ($_FILES as $file) {
$name = basename($file['name']);
$tmp_name = $file['tmp_name'];
$size = $file['size'];
if (move_uploaded_file($tmp_name, "../folder/" .$name)) {
echo $name, ' <progress id="bar" value="100" max="100"> </progress> done <br />';
}
}
I think the glob() function can help:
<?php
foreach(glob("*.jpg") as $picture)
{
echo $picture.'<br />';
}
?>
demo result:
pic1.jpg
pic2.jpg
pic3.jpg
pic4.jpg
...
be sure to change the file path and extension(s) where necessary.
Thanks for the help, i got it to work by simply creating variables:
$image_1 = (print_r($files['name'][0], true));
$image_2 = (print_r($files['name'][1], true));
$image_3 = (print_r($files['name'][2], true));

Categories