PHP move_uploaded_file() only moves the last picture to the folder - php

I have a form though which i want to upload multiple images and store them in my folder, but my program only stores the last selected image.
My form:
<form method="POST" action="server.php" enctype="multipart/form-data">
<input type="file" name="pictures[]" multiple>
<button class="btn btn-success btn-block" name="add">ADD</button>
</form>
My PHP code:
$images = $_FILES['pictures'];
$image_names = $images['name'];
$image_tmpnames = $images['tmp_name'];
foreach($image_names as $image_name){
$foto = 'images/' . $image_name;
foreach($image_tmpnames as $image_tmpname){
move_uploaded_file($image_tmpname,$foto);
}
}
How can I fix this so all of the pictures will be moved to my "images" folder?

maybe try other loop, and set the distination path.
I craft this code you can implement in your solution:
$arquivo = isset($_FILES['img']) ? $_FILES['img'] : FALSE;
for ($controle = 0; $controle < count($arquivo['name']); $controle++){
$destino = $diretorio."/".$arquivo['name'][$controle];
if(move_uploaded_file($arquivo['tmp_name'][$controle], $destino)){
echo "Upload sucess<br>";
}else{
echo "Erro upload";
}
}

Don't use nested loops. You want to process the two arrays in parallel, not as a cross-product.
foreach ($image_names as $i => $image_name) {
$image_tmpname = $image_tmpnames[$i];
$foto = 'images/' . $image_name;
move_uploaded_file($image_tmpname,$foto);
}

Related

Uploading Multiple Files to Location and Updated Database

I have been working on a multi-image upload function that I can't seem to make work. It currently will only work if I have a single image uploaded. I can't figure out what is going wrong with this script.
This is the function to upload images:
if(isset($_POST["btnSubmit"])){
$errors = array();
$extension = array("jpeg","jpg","png","gif");
$bytes = 1000000;
$allowedKB = 10485760000;
$totalBytes = $allowedKB * $bytes;
$imgDir = "assets/users/".$userLoggedIn."/images/";
if(isset($_FILES["files"])==false)
{
echo "<b>Please, Select the files to upload!!!</b>";
return;
}
foreach($_FILES["files"]["tmp_name"] as $key=>$tmp_name)
{
$uploadThisFile = true;
$file_name=$_FILES["files"]["name"][$key];
$file_tmp=$_FILES["files"]["tmp_name"][$key];
$ext=pathinfo($file_name,PATHINFO_EXTENSION);
if(!in_array(strtolower($ext),$extension))
{
array_push($errors, "File type is invalid. Name:- ".$file_name);
$uploadThisFile = false;
}
if($_FILES["files"]["size"][$key] > $totalBytes){
array_push($errors, "File size is too big. Name:- ".$file_name);
$uploadThisFile = false;
}
if($uploadThisFile){
$filename = basename($file_name,$ext);
$newFileName = uniqid().$filename.$ext;
move_uploaded_file($_FILES["files"]["tmp_name"][$key],$imgDir.$newFileName);
// current date and time
$date_added = date("Y-m-d H:i:s");
$imagePath = $imgDir.$newFileName;
$query = "INSERT INTO images(date_added, added_by, image, deleted) VALUES('$date_added', '$userLoggedIn','$imagePath', 'no')";
mysqli_query($con, $query);
}
}
header("Location: edit-images.php");
$count = count($errors);
if($count != 0){
foreach($errors as $error){
echo $error."<br/>";
}
}
}
?>
I thought the issue might be with size but I cut the condition to prevent it from uploading with no luck. I feel like I might be missing something in the foreach but I am completely stuck. I appreciate your help!
Here is the form I am using to upload:
<form method="post" enctype="multipart/form-data" name="formUploadFile" id="uploadForm" action="edit-images.php">
<div class="form-group">
<label for="exampleInputFile">Select file to upload:</label>
<input type="file" id="exampleInputFile" name="files[]" multiple="multiple">
<p class="help-block"><span class="label label-info">Note:</span> Please, Select the only images (.jpg, .jpeg, .png, .gif)</p>
</div>
<button type="submit" class="btn btn-primary" name="btnSubmit" >Start Upload</button>
</form>

How to upload an array of files?

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>

move_uploaded_file in PHP not working?

I'm actively learning php and am working on a CMS Project. I'm stuck on image upload.
PHP
if ( $_POST['img'])
$uploads_dir = '/images';
$tmp_name = $_FILES["img"]["tmp_name"];
$name = $_FILES["img"]["name"];
move_uploaded_file($tmp_name, "$uploads_dir/$name");
HTML
<img src="images/$image" />
MySQL
$sql = "INSERT INTO affordplan VALUES('$title','$name','$bodytext','$created')";
return mysql_query($sql);
The name of the file is uploaded to database but the file itself is not being uploaded to the destination folder.
Type your html code in between form and in the form wrtie as following
<form action="" method="post" enctype="multipart/form-data">
<img src="images/$image" name="img" />
...
</form>
Use $_FILES to check file is posted or not instead of $_POST. Also make proper quote for variables. Then for echo php variable use php tags.
Try
PHP:
if ( $_FILES['img'])
$uploads_dir = 'images'; // will be on same location where php file exist.
$tmp_name = $_FILES["img"]["tmp_name"];
$name = $_FILES["img"]["name"];
move_uploaded_file($tmp_name, $uploads_dir.'/'.$name);
HTML:
<img src="images/<?php echo $image;?>" />
MySQL:
$sql = "INSERT INTO affordplan VALUES('$title','$name','$bodytext','$created')";
return mysql_query($sql);
// Upload multiple files to the folder
$upload_dir = '/images';
if ( $_FILES['img']){
foreach ($_FILES["img"]["error"] as $key => $error) {
if ($error == UPLOAD_ERR_OK) {
$tmp_name = $_FILES["img"]["tmp_name"][$key];
$name = $_FILES["img"]["name"][$key];
move_uploaded_file($tmp_name, "$upload_dir/$name");
}
}
}
//MySQL
MySQL:
$sql = "INSERT INTO affordplan VALUES('$title','$name','$bodytext','$created')";
return mysql_query($sql);
HTML used in form submission
<input type="file" name="img" multiple>
Showing the images in HTML
$dir = "/images/";
$images = glob($dir."*.jpg");
foreach($images as $image) {
echo '<img src="'.$image.'" /><br />';
}
You are assigning a directory that is equivalent to the file name. Try this
<?php
if (!file_exist("your main directory/the file to story")) {
mkdir("your main directory/the file to story", 0777, true);
}
// then you start uploading your once the folder is created
?>
The process here is if the folder directory doesn't exist, the mkdir() function will create that folder. Then that's the time you start on moving the file to the created folder.
Put all of your code in if statement:
if ( $_POST['img']) {
$uploads_dir = '/images';
$tmp_name = $_FILES["img"]["tmp_name"];
$name = $_FILES["img"]["name"];
move_uploaded_file($tmp_name, "$uploads_dir/$name");
}
<form action="phpfilename.php" method="post"
enctype="multipart/form-data">
<input type="file" name="file" id="file" />
<input type="submit" value="Upload Image" name="submit">
$file=$_FILES['file']['name'];
$dest="uploads/$file";
$src=$_FILES['file']['tmp_name'];
move_uploaded_file($src,$dest);
$result=mysql_query("insert into tablename(dbfieldname) values('$dest')");

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

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