How to upload an array of files? - php

I'm trying to build an array of files by submitting a form several times, then move those files to a directory, but it's not working. Every uploads just overrides the previous and then it doesn't even move that one (the upload_to_file() function doesn't do anything)
HTML:
<form id="form" action="home.php" method="post" enctype="multipart/form-data">
<input type="hidden" name="MAX_FILE_SIZE" value="8000000">
<input class="upload_btn" type="file" name="images[]" id="image_file">
<input type="submit" id="img_submit" class="form_button" name="submit_image" value="upload"/>
</form>
It is important that there is only one upload button which can be used to upload many files.
I need them to be stored in an array so I can display their ['name'] anywhere with a loop.for ($i = 0; $i < count($_FILES['images']['name']); $i++){}
Then once another form is submitted it calls a function to move each file in the array to a directory.
Function inside an included php file:
function upload_to_file(){
$image_paths = array();
$target_dir = "uploads/images/";
$path = $target_dir . basename($_FILES['images']['name'][0]);
if(isset($_FILES['images']['name'][0]) && $_FILES['images']['size'][0] > 0)
{
if (move_uploaded_file($_FILES['images']['tmp_name'][0], $path)) {
$image_paths[0] = "uploads/images/";
}
}
return $image_paths;
}
I'm only testing it with the first element in the array, but will need to make a loop later.

Here is the program, which help you to upload multiple files. in the code "sub" is the submit button name. "upload" is the name of file controller, the uploaded files are stored in the directory called "img" that you have to create on your root folder.
<?php
if (isset($_POST['sub'])) {
if (count($_FILES['upload']['name']) > 0) {
for ($i=0; $i<count($_FILES['upload']['name']); $i++) {
$tmpFilePath = $_FILES['upload']['tmp_name'][$i];
if ($tmpFilePath != "") {
$shortname = $_FILES['upload']['name'][$i];
$filePath = "img/" . date('d-m-Y-H-i-s').'-'.$_FILES['upload']['name'][$i];
if (move_uploaded_file($tmpFilePath, $filePath)) {
$files[] = $shortname;
}
}
}
}
echo "<h1>Uploaded:</h1>";
if(is_array($files)){
echo "<ul>";
foreach($files as $file){
echo "<li>$file</li>";
}
echo "</ul>";
}
}
?>
HTML Code is given
<form action="" enctype="multipart/form-data" method="post">
<input id='upload' name="upload[]" type="file" multiple="multiple" />
<input type="submit" name="sub" value="Upload Now">
</form>

Related

Match indexes of two arrays in PHP to pair data

I am doing a form with multiple files upload, for each file input there is a title input and I want to match the title with the file in order to be able to rename the file with the title.
I don't know how to match indexes of the two arrays to be able to do this.
Could someone help me? Thx
Here is my code so far ...
PHP :
$target_dir = 'files/';
if(isset($_POST['title']) && !empty($_POST['title'])){
$total_titles = count($_POST['title']);
for($key = 0; $key < $total_titles; $key++) {
// Clean retrieved client data
$pageName= $_POST['titles'];
}
// Check files
if(isset($_FILES['userfile']['name'])) {
// Count the number of uploaded files
$total_files = count($_FILES['userfile']['name']);
// Loop on uploaded files
for($key = 0; $key < $total_files; $key++) {
// Check if file is selected
if(isset($_FILES['userfile']['name'][$key]) && $_FILES['userfile']['size'][$key] > 0) {
$original_filename = $_FILES['userfile']['name'][$key];
// Get the file extension
$extension = pathinfo($original_filename, PATHINFO_EXTENSION);
// Get filename without extension
$filename_without_extension = basename($original_filename, '.'.$extension);
// Generate new filename
$new_filename = str_replace(' ', '_', $filename_without_extension) . '_' . '.' . $extension;
// Upload the file with new name
move_uploaded_file($_FILES['userfile']['tmp_name'][$key], $target_dir . $new_filename);
}
}
}
}
HTML
<div class="container">
<div class="row justify-content-center">
<!-- Page names -->
<form class="form col-xl-6" action="" id="page_list_section" method="post" enctype="multipart/form-data">
<input type="text" name="title[]" placeholder="Title" >
<input type="file" name="userfile[]" >
<input type="text" name="title[]" placeholder="Title" >
<input type="file" name="userfile[]" >
<input type="submit" name="Submit" value="Upload" >
</form>
</div>
</div>
Here is the match:
for($key = 0; $key < $total_files; $key++) {
$title = $_POST['title'][$key];
$filename = $_FILES['userfile']['name'][$key];
}

php - naming Multiple file input fields on a form

I am wanting to have multiple fields on one form that can insert files.
I have the below script, but I want to be able to identify what field the inserted file belongs to in the saved name.
<form action="" method="post" enctype='multipart/form-data' id="form" name="form">
Input 1<input type="file" name="upload[]" >
Input 2<input type="file" name="upload[]" >
Input 3<input type="file" name="upload[]" >
<button id="submit-button">Upload</button>
</form>
<?php
//if(isset($_POST['submit']) && !empty($_POST) ){
$count = 0;
$max_file_size = 5000000;
if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST"){
// Loop $_FILES to exeicute all files
foreach ($_FILES['upload']['name'] as $f => $name) {
$path = 'documents'; //path of directory
if ($_FILES['upload']['error'][$f] == 4) {
continue; // Skip file if any error found
} else {
if ($_FILES['upload']['size'][$f] > $max_file_size) {
$message[] = "$name is too large!.";
continue; // Skip large files
}
else {
// No error found! Move uploaded files
//$name_of_file = $_FILES['username']['name'][$f];
$temp_name = $_FILES['upload']['tmp_name'][$f]; //[$count];
move_uploaded_file($temp_name, "$path/"."$name");
$count++; // Number of successfully uploaded file
}
}
}
}
At the moment it just saves the files into the one location, so I cant differentiate them and identify which field they are from.
can anyone please help?
I have worked it out. I have taken the comments above and placed an Text input field at each of the File Fields. These could also be hidden fields if you need set names.
Then I scroll through them and save the names and apply those names on the server side.
Thanks to the comments, they helped me see the solution.
<form action="" method="post" enctype='multipart/form-data' id="form" name="form">
<input type="text" name="input0" value=""><input type="file" name="upload[]" ><br><br>
<input type="text" name="input1" value=""><input type="file" name="upload[]" ><br><br>
<input type="text" name="input2" value=""><input type="file" name="upload[]" ><br><br>
<button id="submit-button">Upload</button>
</form>
<?php
$count = 0;
$max_file_size = 500000000000;
if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST"){
// Loop $_FILES to exeicute all files
$x = 0;
$input = "input";
while ($x <= 2){
$field_name = $input.$x;
$field[$x] = $_POST[$field_name];
$x++;
}
foreach ($_FILES['upload']['name'] as $f => $name) {
$path = 'documents'; //path of directory
if ($_FILES['upload']['error'][$f] == 4) {
continue; // Skip file if any error found
} else {
if ($_FILES['upload']['size'][$f] > $max_file_size) {
$message[] = "$name is too large!.";
continue; // Skip large files
}
else {
$temp_name = $_FILES['upload']['tmp_name'][$f]; //[$count];
move_uploaded_file($temp_name, "$path/"."$field[$count]"."$name");
$count++; // Number of successfully uploaded file
}
}
}
}

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));

How to move an uploaded file

I have an HTML web form where users can upload multiple files. I am having trouble with moving the files though.
HTML:
My HTML:
<form enctype="multipart/form-data" method="post" action="save.php">
<input type="hidden" name="MAX_FILE_SIZE" value="500000"/>
<input type="file" name="uploads[]" multiple="multiple" />
<input type="submit" name="submit" value="submit"/>
</form>
Save.php:
<?php
foreach ($_FILES['uploads']['name'] as $file) {
$target= UPLOADPATH . $file;
move_uploaded_file($file, $target)
or die('error with moving the file');
$file= time() . $_FILES['uploads']['name'];
echo $file;
}
The problem is with move_uploaded_file(). What could I be doing wrong?
Try as below, you need to pass first parameter as file source
foreach ($_FILES['uploads']['name'] as $key => $file) {
$target= UPLOADPATH . $file;
move_uploaded_file($_FILES['uploads']['tmp_name'][$key], $target)
or die('error with moving the file');
$file= time() . $_FILES['uploads']['name'];
echo $file;
}

Uploading files with PHP

I am using a form for users to upload files to my website. I want to allow them to upload multiple photos at once, so I am using the HTML5 "multiple" attribute.
My HTML:
<form method="post" action="save.php">
<input type="file" name="uploads[]" multiple="multiple" />
<input type="submit" name="submit" value="submit"/>
</form>
save.php:
<?php
foreach ($_FILES['uploads']['name'] as $file) {
echo $file . "<br/>";
$file= time() . $_FILES['uploads']['name'];
$target= UPLOADPATH . $file;
move_uploaded_file($_FILES['uploads']['tmp_name'], $target)
or die('error with query 2');
}
But, for some reason when I run the script, I get an error saying undefined index: uploads. And an error saying that I have an invalid argument supplied for foreach(). What could I be dong wrong?
Thanks
UPDATE
Okay, setting the enctype="mulitpart/form-data" worked. Now, I am having trouble with moving the file. I am getting the error move_uploaded_file() expects parameter 1 to be string, array given. What am I doing wrong here?
Thanks again
You need the proper enctype to be able to upload files.
<form method="post" enctype="multipart/form-data" action="save.php">
try this html code: <form method="post" action="save.php" enctype="multipart/form-data">
Then in PHP:
if(isset($_FILES['uploads'])){
foreach ($_FILES['uploads']['name'] as $file) {
echo $file . "<br/>";
$file= time() . $_FILES['uploads']['name'];
$target= UPLOADPATH . $file;
move_uploaded_file($_FILES['uploads']['tmp_name'], $target)
or die('error with query 2');
}
} else {
echo 'some error message!';
}
In order to upload files in the first place, you need enctype="multipart/form-data" on your <form> tag.
But, when you upload multiple files, every key in $_FILES['uploads'] is an array (just like $_FILES['uploads']['name']).
You need to get the array key when looping, so you can process each file. See the docs for move_uploaded_file for more deatils.
<?php
foreach ($_FILES['uploads']['name'] as $key=>$file) {
echo $file."<br/>";
$file = time().$file;
$target = UPLOADPATH.$file;
move_uploaded_file($_FILES['uploads']['tmp_name'][$key], $target)
or die('error with query 2');
}
index.html
<form method="post" action="save.php" enctype="multipart/form-data">
<input type="file" name="uploads[]" multiple="multiple" />
<input type="submit" name="submit" value="Upload Image"/>
</form>
save.php
<?php
$file_dir = "uploads";
if (isset($_POST["submit"])) {
for ($x = 0; $x < count($_FILES['uploads']['name']); $x++) {
$file_name = time() . $_FILES['uploads']['name'][$x];
$file_tmp = $_FILES['uploads']['tmp_name'][$x];
/* location file save */
$file_target = $file_dir . DIRECTORY_SEPARATOR . $file_name;
if (move_uploaded_file($file_tmp, $file_target)) {
echo "{$file_name} has been uploaded. <br />";
} else {
echo "Sorry, there was an error uploading {$file_name}.";
}
}
}
?>

Categories