Issue on Uploading Multiple Images to Server By One Click - php

I am trying to upload multiple images to server by one click. I am not getting any error on JavaScript console but no images uploaded to the server. Can you please let me know what I am doing wrong?
Here is my HTML markup
<form id="uploadimage" action="" method="post" enctype="multipart/form-data">
<div class="row">
<div class="col-xs-6 col-md-3 text-center">
<a href="#" class="thumbnail ">
<div class="img-box">
<input type="file" class="file" name="image" /> <img class="img img-responsive" />
</div>
</a>
</div>
<div class="col-xs-6 col-md-3 text-center">
<a href="#" class="thumbnail ">
<div class="img-box">
<input type="file" class="file" name="image" />
<img class="img img-responsive" />
</div>
</a>
</div>
</div>
<input type="submit" value="Upload" class="submit" />
</form>
js file as:
$("#uploadimage").on('submit', (function(e) {
e.preventDefault();
$.ajax({
url: "loader.php",
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData: false,
success: function(data) {
}
});
}));
and PHP (loader.php) as
<?php
if (isset($_FILES["file"]["type"])) {
$validextensions = array(
"jpeg",
"jpg",
"png"
);
$temporary = explode(".", $_FILES["file"]["name"]);
$file_extension = end($temporary);
if ((($_FILES["file"]["type"] == "image/png") || ($_FILES["file"]["type"] == "image/jpg") || ($_FILES["file"]["type"] == "image/jpeg")) && ($_FILES["file"]["size"] < 100000) //Approx. 100kb files can be uploaded.
&& in_array($file_extension, $validextensions)) {
if ($_FILES["file"]["error"] > 0) {
echo "Return Code: " . $_FILES["file"]["error"] . "<br/><br/>";
} else {
if (file_exists("upload/" . $_FILES["file"]["name"])) {
echo $_FILES["file"]["name"] . " <span id='invalid'><b>already exists.</b></span> ";
} else {
$sourcePath = $_FILES['file']['tmp_name']; // Storing source path of the file in a variable
$targetPath = "upload/" . $_FILES['file']['name']; // Target path where file is to be stored
move_uploaded_file($sourcePath, $targetPath); // Moving Uploaded file
echo "<span id='success'>Image Uploaded Successfully...!!</span><br/>";
}
}
} else {
echo "<span id='invalid'>***Invalid file Size or Type***<span>";
}
}
?>\

Please refer this .
when you send multiple files, php accept it as an array of files but in your code you are accepting them as a single file.
Also, try to give array of name as
<input type="file" name="images[]" id="images" multiple >

In a form, the name is the identifier of the input. So you should do $_FILES["image"] to access your file.
When a form have multiple inputs with the same name, it must be name with [] at the end (at least in php). So rename your image[] in the html source.

first, your file array you are taking in controller is wrong,
$temporary = explode(".", $_FILES["file"]["name"]);
you need to take image instead of file because in form file input name you used is image so,
$temporary = explode(".", $_FILES["image"]["name"]);
then after in your html you can take like this as thisisme_22 suggests
<input type="file" name="images[]" id="images" multiple >
then after in you action php file you can take count of the files and the using for or foreach you can get single file and upload it, like this
$count = count($FILES['image']['name']);
for($i = 0 ; $i < $count ; $i++){
$file = $FILES['image']['name'][$i];
}
I hope it helps.

check this code and change it as you need
$arr = array();
$arr = $_FILES['image']['name'];
for($i = 0; $i < count($arr) ; $i++)
{
$file_name = $_FILES['image']['name'][$i];
$file_size = $_FILES['image']['size'][$i];
$file_tmp = $_FILES['image']['tmp_name'][$i];
$file_type = $_FILES['image']['type'][$i];
$responce = move_uploaded_file($file_tmp, "orders/".$file_name);
}

Related

How to upload multiple file and move into folder in php?

code:
<?php
if(isset($_POST['submit']))
{
if(isset($_FILES['img_url']['name']))
{
for($i=0; $i<count($_FILES['img_url']['name']); $i++)
{
$tmpFilePath = $_FILES['img_url']['tmp_name'][$i];
if ($tmpFilePath != "")
{
$path = "../images/hotel_images/";
$name = $_FILES['img_url']['name'][$i];
$size = $_FILES['img_url']['size'][$i];
list($txt, $ext) = explode(".", $name);
$file= time().substr(str_replace(" ", "_", $txt), 0);
$info = pathinfo($file);
$filename = $file.".".$ext;
$filepath_upload = $path.$filename;
$imageFileType = strtolower(pathinfo($filename,PATHINFO_EXTENSION));
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg" && $imageFileType != "gif" )
{
$j2 = $i+1;
$msg = "<div class='alert alert-success'>Sorry, ".$j2." Image files Extension .".$ext." are not Uploaded & Other files Uploaded Successfully <br/>.</div>" ;
}
else if(move_uploaded_file($_FILES['img_url']['tmp_name'][$i], $filepath_upload))
{
$banner_image_source_file = $filepath_upload;
$banner_image_save_file = $filepath_upload;
list($width_orig, $height_orig) = getimagesize($banner_image_source_file);
$img_url_name.=$filename."|";
}
}
$filepath = rtrim($img_url_name, '|');
}
if(!empty($filepath))
{
$query = mysqli_query($con, "INSERT INTO `hotel`(`img_url`, `status`) VALUES ('".$filepath."')");
if($query)
{
$msg .= "<div class='alert alert-success'>Hotel Record Added Successfully</div>";
}
else
{
$msg = "<div class='alert alert-success'>Unbale to Add Hotel Record Please Try Again !!!</div>";
}
}
else
{
$msg = "<div class='alert alert-success'>Unable to Add Please Try Again !! </div>";
}
}
else
{
$msg = "<div class='alert alert-success'>Unable to Add Please Try Again !! </div>";
}
}
?>
<form action="" method="POST" enctype="multipart/form-data" id="add-hotel-form">
<div class="form-group col-md-12">
<label for="hotel">Upload Hotel Images</label>
<input type="file" class="form-control-file" id="upload_hotel_img1" name="img_url[]" multiple>
</div>
<div class="form-group col-md-12">
<label for="room">Upload Room Images</label>
<input type="file" class="form-control-file" id="upload_room_img1" name="img_url2[]" multiple>
</div>
<input type="submit" class="btn btn-primary" name="submit" value="Submit">
</form>
In the following code I have create a simple form where I have two input field type='file' where I am able to upload only first one i.e. <label for="hotel">Upload Hotel Images</label> and move into the folder successfully but I also want to upload and move second input field i.e. <label for="room">Upload Room Images</label>. I don't have any idea about this. So, How can I do this? Please help me.
Thank You
Your Room Image input is called img_url2, which you never interact with in code.
For best practice, move the bulk of your PHP code into a file upload function, then call it once with img_url $_FILE input, and once with img_url2.
Example:
<?php
error_reporting(E_ALL);
ini_set("display_errors", true);
ini_set("display_startup_errors", true);
function uploadFile($file, $path)
{
$img_url_name = "";
if(is_array($file) && isset($file['name']) && isset($file['tmp_name']) && isset($file['size']))
{
$tmpFilePath = isset($file['tmp_name'][0]) ? $file['tmp_name'][0] : "";
$name = isset($file['name'][0]) ? $file['name'][0] : "";
list($txt, $ext) = explode(".", $name);
$file = time().substr(str_replace(" ", "_", $txt), 0);
$filename = $file.".".$ext;
$filepath_upload = $path.$filename;
$imageFileType = strtolower(pathinfo($filename,PATHINFO_EXTENSION));
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg" && $imageFileType != "gif" )
{
return "<div class='alert alert-success'>Sorry, ".$name." Image files Extension .".$ext." are not Uploaded & Other files Uploaded Successfully <br/>.</div>" ;
}
else if(move_uploaded_file($tmpFilePath, $filepath_upload))
{
$img_url_name .= $filename."|";
}
$filepath = rtrim($img_url_name, '|');
if(!empty($filepath))
{
if(!isset($con))
{
global $con;
}
$query = mysqli_query($con, "INSERT INTO `hotel`(`img_url`, `room_url`) VALUES ('".$filename."','".$filepath."')");
if($query)
{
return "<div class='alert alert-success'>Hotel Record Added Successfully</div>";
}
}
}
return "<div class='alert alert-success'>Unable to Add Please Try Again !! </div>";
}
if(isset($_POST['submit']))
{
if(isset($_FILES['img_url']['name']))
{
echo uploadFile($_FILES['img_url'], "../images/hotel_images/");
}
if(isset($_FILES['img_url2']['name']))
{
echo uploadFile($_FILES['img_url2'], "../images/room_img/");
}
}
?>
<form action="" method="POST" enctype="multipart/form-data" id="add-hotel-form">
<div class="form-group col-md-12">
<label for="hotel">Upload Hotel Images</label>
<input type="file" class="form-control-file" id="upload_hotel_img1" name="img_url" multiple>
</div>
<div class="form-group col-md-12">
<label for="room">Upload Room Images</label>
<input type="file" class="form-control-file" id="upload_room_img1" name="img_url2" multiple>
</div>
<input type="submit" class="btn btn-primary" name="submit" value="Submit">
</form>
I use FormData() to upload multiple images from multiple fields. Please take a look at this code:
<head>
<title>Example</title>
</head>
<body>
<form enctype="multipart/form-data" id="add-hotel-form">
<div class="form-group col-md-12">
<label for="hotel">Upload Hotel Images</label>
<input type="file" class="form-control-file" id="upload_hotel_img1" name="img_url" multiple>
</div>
<div class="form-group col-md-12">
<label for="room">Upload Room Images</label>
<input type="file" class="form-control-file" id="upload_room_img2" name="img_url2" multiple>
</div>
<input type="button" class="btn btn-primary" name="submit" value="Submit" onclick="myfunction();">
</form>
</body>
<script>
function myfunction(){
var form_data = new FormData();
var image = document.getElementById('upload_hotel_img1').files.length;
var images = document.getElementById('upload_room_img2').files.length;
for (var x = 0; x < image; x++) {
form_data.append("image", document.getElementById('upload_hotel_img1').files[x]);
}
for (var x = 0; x < images; x++) {
form_data.append("images[]", document.getElementById('upload_room_img2').files[x]);
}
}
</script>
We can retrieve these images in the backend using the follwing : $_FILES["image"]['name'] and $_FILES["images"]['name'] respectively.

PHP File Upload Not Submitting

I'm having an issue with a file upload where it's not uploading. When uploading a 7mb video the $_FILES['video']['tmp_name'] is empty and when I upload a 15mb file the form doesn't actually "submit", really just refreshes.
Here is my code to handle the submission:
if(isset($_POST['submit'])){
$blah = "".$_FILES['video']['size']."";
var_dump($blah);
if( empty($_FILES['video']) && empty($_POST['create_video']) ){
echo "<div class='alert alert-danger' role='alert'><center><strong>Missing Fields:</strong> Please choose a video or request the ##### team create a video.</center></div>";
} else {
if( empty($_FILES['video']['name']) && $_POST['create_video'] == "true" ){
$_SESSION['create_video'] = protect($_POST['create_video']);
?>
<script type="text/javascript">
window.location = "NEXT_PAGE";
</script>
<?
exit();
}else{
//if all were filled in continue
$allowedExts = array("mp4", "MP4", "m4a");
$extension = pathinfo($_FILES['video']['name'], PATHINFO_EXTENSION);
if ( ($_FILES["video"]["size"] <= 15728640) && (in_array($extension, $allowedExts)) ) {
if ($_FILES["video"]["error"] > 0){
echo "Return Code: " . $_FILES["video"]["error"] . "<br />";
}else{
//Get the height and width of our video
//$getID3 = new getID3;
//$file = $getID3->analyze($_FILES["video"]["tmp_name"]);
//$width =$file['video']['resolution_x'];
//$height = $file['video']['resolution_y'];
$img = getimagesize($_FILES['video']['tmp_name']);
$width = $img[0];
$height = $img[1];
var_dump($width); var_dump($height);
if( ($height < 719) || ($width < 1279)){
echo "<div class='alert alert-danger' role='alert'><center><strong>Invalid file dimensions</strong> Please ensure your image is the correct size.</center></div>";
} else {
$ext = findexts ($_FILES["video"]["name"]);
$ran = rand ();
$file_name = $_FILES["video"]["name"] = "".$_SESSION['uid'] ."".$ran.".".$ext."";
if (file_exists("uploads/video_ads/".$_SESSION['uid']."_" . $_FILES["video"]["name"])){
echo $_FILES["video"]["name"] . " already exists. ";
}else{
move_uploaded_file($_FILES["video"]["tmp_name"],
"uploads/video_ads/".$_SESSION['uid']."_" . $_FILES["video"]["name"]);
//Save the link of our ad
$_SESSION['video'] = "####/uploads/video_ads/".$_SESSION['uid']."_" . $_FILES["video"]["name"]."";
$_SESSION['create_video'] = protect($_POST['create_video']);
?>
<script type="text/javascript">
window.location = "NEXT_PAGE";
</script>
<?
exit();
}
}
}
} else {
echo "<div class='alert alert-danger' role='alert'><center><strong>Invalid file type</strong> Please upload a video in MP4 format.</center></div>";
}
}
}
}
Here is my actual form:
<form action="<? echo $_SERVER['PHP_SELF']; ?>" method="post" class="form-signin" role="form" enctype="multipart/form-data">
<br />
<input type="file" name="video" id="video" /><br />
<br />
<div class="row">
<div class="col-md-12">
<strong class="ad-header"
style="font-size: 150%; font-weight: bold;">Quick Tips:</strong>
</div>
</div>
<hr>
<h3 class="ad-sub-header" style="color: #559fd3; font-size: 150%;">Need
help to create engaging artwork for your brand?</h3>
<strong class="ad-header" style="font-size: 100%;">####
has the creative team to get it done for you</strong><br /> Only ##/hr -
3 revisions - Artwork is yours to keep. <br />
<br /> <input type="checkbox" name="create_video" value="true" />
I don't have an ad. Please create one. <br />
<br /> <input class="btn btn-lg btn-primary btn-block"
type="submit" name="submit" value="Continue To Step 5" />
</form>
The odds are your server does not accept uploads greater than 2M in size. You need to check phpinfo() (or php.ini if you have access to it) to see what your current limit is. If it is only 2M, or smaller than your upload size, you need to edit it to allow for bigger uploads. If you're on shared hosting you may be out of luck.
Try adjusting your php.ini with this settings:
php_value memory_limit 96M
php_value post_max_size 96M
php_value upload_max_filesize 96M
and ensure that the file_uploads setting is in On
For anyone who has this issue. I had to increase my post_max_size which was defaultly set to 8M.

add limit php upload image

I use a php ajax script for uploading image in my site and it's don't has limit for upload image.
I want a user can upload only for example 3 image. how can add this limit in my code?
This is my php code for uploading image:
if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST")
{
$vpb_upload_image_directory = "uploads/";
$vpb_allowed_extensions = array("gif", "jpg", "jpeg", "png");
foreach($_FILES as $file)
{
/* Variables Declaration and Assignments */
$vpb_image_filename = basename($file['name']);
$vpb_image_tmp_name = $file['tmp_name'];;
$vpb_file_extensions = pathinfo(strtolower($vpb_image_filename), PATHINFO_EXTENSION);
//New file name
$random_name_generated = time().rand(1234,9876).'.'.$vpb_file_extensions;
if($vpb_image_filename == "")
{
//Browse for a photo that you wish to use
}
else
{
if (in_array($vpb_file_extensions, $vpb_allowed_extensions))
{
if(move_uploaded_file($vpb_image_tmp_name, $vpb_upload_image_directory.$random_name_generated))
{
//Display Uploaded Files
$image .= '
<div class="vpb_wrapper" style="padding:10px;">
<img src="'.$vpb_upload_image_directory.$random_name_generated.'" class="vpb_image_style" />
</div>';
//$image .= '<div class="vpb_wrapper" style="padding:10px; text-decoration:none;">'.$vpb_image_filename.' uploaded</div>';
}
}
else
{
// Do not upload files which are not in the allowed file array
}
}
}
//Display the files
if($image != "") echo $image;
}
?>
In javascript, you can do something like this,
$(document).ready(function(){
$('#photoUploader').click(function(){
$('#photoUI').toggle('slow');
});
var ctr = 1;
$('#add').click(function(){
if(ctr < 3)
{
$('#ulPhoto').append("<li><input type='file' name='file[]' onchange='loadPreview(this,"+ctr+")' id='photo"+ctr+"' /><br /><img id='img"+ctr+"' src='#' alt='' style='width:100px' /><input type='text' autocomplete='off' name='caption[]' id='caption"+ctr+"' placeholder='ID Number' /></li>");
ctr++;
}
else
{
alert('Only 3 Images Allowed at a time');
}
});
});
HTML
<div id="photoUI" style="display:none; height: auto">
<ul id="ulPhoto">
<li>
<input type="file" name="file[]" id="photo0" />
<br />
<img id="img0" src="#" alt="" style="width:100px" />
<input type="text" autocomplete="off" name="caption[]" onchange="loadPreview(this,0)" id="caption0" placeholder="Default ID Number" readonly disabled />
</li>
</ul>
<span id="add" style="cursor:pointer">Add More...</span>
</div>

post multiple image using 1 field in a form

My code in here. how can I upload more then 1 image using 1 input field?
<?php
if (isset($_POST['beopen_form'])) {
if ($_FILES["file1"]["error"] > 0) {
echo "Error: " . $_FILES["file1"]["error"] . "<br>";
} else {
$x = mysql_insert_id();
$path_array = wp_upload_dir();
$old_name = $_FILES["file1"]["name"];
$split_name = explode('.', $old_name);
$time = time();
$file_name = $time . "." . $split_name[1];
$tmp_name = $_FILES["file1"]["tmp_name"];
move_uploaded_file($_FILES["file"]["tmp_name"], $path . "/" . $old_name);
$path2 = $path . "/" . $old_name;
mysql_query("INSERT INTO carimage (image,carid,created,updated) VALUES ('$path2','$x','$created','$updated') ON DUPLICATE KEY UPDATE image='$path2',description='$makeid',updated='$updated'");
}
}
?>
<form enctype="multipart/form-data" class="beopen-contact-form" id="signupForm" novalidate="novalidate" action="<?php echo get_permalink(); ?>" method="post">
<input type="file" name="file" id="file">
<div id="recaptcha_div"></div><br>
<input type="hidden" name="beopen_form" value="1" /><!-- button -->
<button class="button send-message" type="submit">
<span class="send-message"></span><?php _e('Update', 'beopen');?>
</button>
</form>
html :-
<input type="file" name="file" id="file" multiple>
PHP CODE:-
//Loop through each file
for($i=0; $i<count($_FILES['file']['name']); $i++) {
//Get the temp file path
$tmpFilePath = $_FILES['file']['tmp_name'][$i];
//Make sure we have a filepath
if ($tmpFilePath != ""){
//Setup our new file path
$newFilePath = "./uploadFiles/" . $_FILES['file']['name'][$i];
//Upload the file into the temp dir
if(move_uploaded_file($tmpFilePath, $newFilePath)) {
//Handle other code here
}
}
}
I TAKE THIS CODE FROM :-
Multiple file upload in php
Before Post any question you should search for problem....!!!

Edit File Image Upload using PHP

I've been having issues with file upload. After help on this site I managed to upload the files successfully to the db and can pull them back to show the images.Part of my assessment is the fact I need the ability to edit my photo choices (by say choosing a different image and maybe keeping one or two the same) and then the user can submit any changes they may wish to make.So on a separate file called 'edit.php' I have pre-populated all the other data that was entered in the db (this works fine) My code looks like:
<label for ="file">Filename:</label>
<?php echo "<img src='upload/".$_FILES['filename']."' />"; ?>
<input type="file" name="file[]" id="file" >
<?php echo "<img src='upload/".$_FILES['filename']."' />"; ?>
<input type="file" name="file[]" id="file" >
<?php echo "<img src='upload/".$_FILES['filename']."' />"; ?>
<input type="file" name="file[]" id="file" >
PHP:
$name = strtolower($name);
$allowedExts = array("gif", "jpeg", "jpg", "png");
$temp = explode(".", $name);
$extension = end($temp);
if(in_array($extension, $allowedExts))
{
if($_FILES['file']['size'][$f] < 2000000)
{
$uniqid = uniqid();
move_uploaded_file($_FILES["file"]["tmp_name"][$f], "upload/" . $uniqid . "." . $extension);
mysql_query("INSERT INTO vehiclesimages (vehicleid, filename) VALUES (".$last_id.", '".$uniqid .".".$extension."')");
}
else
{
echo "File size to big!";
}
}
else
{
echo "Image not supported, please try again!";
}
Any ideas/help or useful sites would be greatly appreciated.As I have been unable to research any info on the subject.

Categories