Getting details selected images in php - php

I'm using html5 js to upload multiple images. Why when we upload multiple images does the result (PHP: print_r($_FILES['upimg']['name'])) only shows details of the last selected image?
For Example:(i selected following image name)
111111.gif
222222.gif
333333.gif
PHP code only last selected image show: 333333.gif
But I want to show details from all the images.
What do I do?
DEMO: http://codepad.viper-7.com/16abeG
FULL CODE:
<!doctype html>
<html>
<head>
<?php
if($_FILES){
echo '<pre>';
print_r($_FILES['upimg']['name']);
//for($i=0; $i<count($_FILES['name']); $i++){
//if ($_FILES['error'][$i] == 0) {
////do your stuff here, each image is at $_FILES['tmp_name'][$i]
//}
//}
}
?>
<title>file input click() demo</title>
<script type="text/javascript">
function doClick() {
var el = document.getElementById("fileElem");
if (el) {
el.click();
}
}
function handleFiles(files) {
var d = document.getElementById("fileList");
if (!files.length) {
d.innerHTML = "<p>No files selected!</p>";
} else {
var list = document.createElement("ul");
d.appendChild(list);
for (var i=0; i < files.length; i++) {
var li = document.createElement("li");
list.appendChild(li);
var img = document.createElement("img");
img.src = window.URL.createObjectURL(files[i]);;
img.height = 60;
img.onload = function() {
window.URL.revokeObjectURL(this.src);
}
li.appendChild(img);
var info = document.createElement("span");
info.innerHTML = files[i].name + ": " + files[i].size + " bytes";
li.appendChild(info);
}
}
}
</script>
</head>
<body>
<p>This is a demo of calling <code>click()</code> on a form's file picker.
Note that the file input element is actually hidden here, so the
user doesn't have to see the path to the selected file.</p>
Select some files
<div id="fileList">
<p>No files selected!</p>
</div>
<form action="#" method="post" enctype="multipart/form-data">
<input name="upimg[]" type="file" id="fileElem" multiple accept="image/*" style="display:none" onchange="handleFiles(this.files)">
<input type="submit" value="Click to see the result">
</form>
</body>
</html>

Your logic i think is wrong you use HTML 5, but not upload images via AJAX you use form for this method.
Miltiple is only HTML 5 and you can't use for PHP purpose without AJAX.
I created similar plugin you can check : https://github.com/dimitardanailov/js-control-files-uploader

Try wrapping it in a for loop somewhat like the code you have commented out....
if(isset($_FILES["upimg"]["name"])) {
for($i=0; $i<count($_FILES["upimg"]["name"]);$i++) {
echo $_FILES["upimg"]["name"][$i];
}
}

why don't you use tag before any of the .parent div?
for width ratio you of course can do it using jquery.
myElement.width = (parentElement.width/100)*40

Related

How to upload multiple images to a folder using ajax php and jquery

I am trying to upload multiple images to a folder at a time by using AJAX, JQuery, and PHP. The code is running for single file upload but not running for multiple image upload.
If I am uploading a single image without loop then its working fine but in case of loop it's not working.
I am using the following code.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Upload Iamge</title>
<link href="style.css" rel="stylesheet" type="text/css">
<script src="jquery-1.12.0.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#but_upload").click(function(){
var fd = new FormData();
//following code is working fine in for single image upload
// var files = $('#file')[0].files[0];
// fd.append('file',files);
//this code not working for multiple image upload
var names = [];
for (var i = 0; i < $('#file').get(0).files.length; ++i) {
names.push($('#file').get(0).files[i].name);
}
fd.append('file[]',names);
/*var ins = document.getElementById('file').files.length;
for (var x = 0; x <ins; x++) {
fd.append("file", document.getElementById('file').files[x]);
}*/
$.ajax({
url:'upload.php',
type:'post',
data:fd,
contentType: false,
processData: false,
success:function(response){
if(response != 0){
$("#img").attr("src",response);
}
},
error:function(response){
alert('error : ' + JSON.stringify(response));
}
});
});
});
</script>
</head>
//HTML Part
<body>
<div class="container">
<h1>AJAX File upload</h1>
<form method="post" action="" id="myform">
<div>
<img src="" id="img" width="100" height="100">
</div>
<div>
<input type="file" id="file" name="file" multiple="multiple" />
<input type="button" class="button" value="Upload"
id="but_upload">
</div>
</form>
</div>
</body>
</html>
//PHP Code
<?php
/* Getting file name */
echo "<script>alert('yes');</script>";
//without loop working fine
$count = count($_FILES['file']['name']);
for ($i = 0; $i < $count; $i++) {
$filename = $_FILES['file']['name'][$i];
/* Location */
$location = "upload/".$filename;
/* Upload file */
if(move_uploaded_file($_FILES['file']['tmp_name'],$location)){
echo $location;
} else {
echo 0;
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Upload Iamge</title>
<script type="text/javascript">
$(document).ready(function(){
$("#but_upload").click(function(){
var fd = new FormData();
//following code is working fine in for single image upload
// var files = $('#file')[0].files[0];
// fd.append('file',files);
//this code not working for multiple image upload
var names = [];
var file_data = $('input[type="file"]')[0].files;
// for multiple files
for(var i = 0;i<file_data.length;i++){
fd.append("file_"+i, file_data[i]);
}
fd.append('file[]',names);
/*var ins = document.getElementById('file').files.length;
for (var x = 0; x <ins; x++) {
fd.append("file", document.getElementById('file').files[x]);
}*/
$.ajax({
url:'upload.php',
type:'post',
data:fd,
contentType: false,
processData: false,
success:function(response){
if(response != 0){
$("#img").attr("src",response);
}
},
error:function(response){
alert('error : ' + JSON.stringify(response));
}
});
});
});
</script>
</head>
//HTML Part
<body>
<div class="container">
<h1>AJAX File upload</h1>
<form method="post" action="" id="myform">
<div>
<img src="" id="img" width="100" height="100">
</div>
<div>
<input type="file" id="file" name="file" multiple="multiple" />
<input type="button" class="button" value="Upload"
id="but_upload">
</div>
</form>
</div>
</body>
</html>
have made changes in below code
var file_data = $('input[type="file"]')[0].files; // for multiple files
for(var i = 0;i<file_data.length;i++){
fd.append("file_"+i, file_data[i]);
}
fd.append('file[]',names);
And there are also changes in PHP code
<?php
/* Getting file name */
//without loop working fine
$count = count($_FILES);
for ($i = 0; $i < $count; $i++) {
$filename = $_FILES['file_'.$i];
/* Location */
echo $location = "upload/".$filename['name'];
/* Upload file */
if(move_uploaded_file($filename['tmp_name'],$location)){
echo $location;
} else {
echo 0;
}
}
?>
count of files and file name are comming in a different way so I have made the changes as required instead of if gives file array like $_FILE['file_0'],$_FILE['file_1'] and so on, I have also change the permission of upload directory please check if your directory have read and write permission (777) or not, this code works for me you can try I hope it will work for you also :-)
In the loop you will need to add index of particular file
move_uploaded_file($_FILES['file']['tmp_name'][$i],$location); // $i is index

uploadprogress_get_info installed correctly and but not working in different code

I know I have no issues with installing uploadprogress extension because when I tried this very simple tutorial: http://www.ultramegatech.com/2010/10/create-an-upload-progress-bar-with-php-and-jquery/, it worked beautifully!
I then tweaked it just a little bit to have a very simple (not jQuery-UI) progress bar, which also worked. Here's the working code:
upload_getprogress.php:
<?php
if (isset($_GET['uid'])) {
$status = uploadprogress_get_info($_GET['uid']);
if ($status) {
echo round($status['bytes_uploaded']/$status['bytes_total']*100);
}
else {
echo 100;
}
}
?>
upload_form.php:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Upload Something</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<style>
#progress-bar, #upload-frame {
display: none;
}
</style>
<script>
(function ($) {
var pbar;
var started = false;
$(function () {
$('#upload-form').submit(function() {
$('#upload-form').hide();
pbar = $('#progress-bar');
pbar.show();
$('#upload-frame').load(function () {
started = true;
});
setTimeout(function () {
updateProgress($('#uid').val());
}, 1000);
});
});
function updateProgress(id) {
var time = new Date().getTime();
$.get('upload_getprogress.php', { uid: id, t: time }, function (data) {
var progress = parseInt(data, 10);
if (progress < 100 || !started) {
started = progress < 100;
updateProgress(id);
}
started && $('#inner').css('width', progress+ "%");
});
}
}(jQuery));
</script>
<style>
#progress-bar
{
height:50px;
width:500px;
border:2px solid black;
background-color:white;
margin:20px;
}
#inner
{
height:100%;
background-color:orange;
width:0%;
}
</style>
</head>
<body>
<form id="upload-form"
method="post"
action="upload.php"
enctype="multipart/form-data"
target="upload-frame" >
<input type="hidden"
id="uid"
name="UPLOAD_IDENTIFIER"
value="<?php echo $uid; ?>" >
<input type="file" name="file">
<input type="submit" name="submit" value="Upload!">
</form>
<div id="progress-bar"><div id='inner'></div>
<iframe id="upload-frame" name="upload-frame"></iframe>
</body>
</html>
All fine and dandy, no issues! So I know for a fact there is nothing wrong with the way I've set up the uploadprogress extension.
However, having completed the demo successfully, I needed to integrate it into my javascript and jQuery intensive web-app, which includes file uploads.
Now when I try it, I get “NULL” from the uploadprogress_get_info() function. Why?
In my application page, my image upload form is created dynamically. But at the beginning of my page (and before the user hits a button that dynamically creates an image upload form), I am using this line:
<input type='hidden' name='UPLOAD_IDENTIFIER' id='uid' value='<?php echo md5(uniqid(mt_rand())); ?>' />
Is this the problem? Is there a specific time or place this hidden input should be present?
Before including the above line at the top of my page, I've also included a long .js file that includes a bunch of jQuery plugins, but starts with the following code:
var started = false;
function updateProgress(id) {
console.log("updating progress"); // this msg appears, so i know i'm getting this far
var time = new Date().getTime();
$.get('upload_getprogress.php', { uid: id, t: time }, function (data) {
var progress = parseInt(data, 10);
if (progress < 100 || !started) {
started = progress < 100;
updateProgress(id);
}
//started && pbar.progressbar('value', progress);
$('#inner').css('width', progress+ "%");
});
}
// a lot more functions, then:
function imageDialog(imgtype, x, y, editsource) {
// this function dynamically generates a dialog for image uploading
// which shows up when a user hits an "image upload" button
// there's lots of code that creates a new form which is assigned to $imgform
// lots of elements and a couple of iframes are appended to $imgform
// then finally:
$imgform.submit(function() {
pbar = $('#progress-bar');
$('#inner').css('width', "0%");
pbar.show();
started = true;
setTimeout(function () {
updateProgress($('#uid').val());
}, 1000);
});
/* other irrelevant stuff */
}
However, while the upload progress bar shows up as expected, it never increases in progress.
So I edited the upload_getprogress.php to look like this:
if (isset($_GET['uid'])) {
$uid = $_GET['uid'];
//$status = uploadprogress_get_info($_GET['uid']);
echo "progress for $uid is: ".uploadprogress_get_info($uid);
}
In Firefox, I can see the response of the ajax call, and what I get as output from upload_getprogress.php is:
progress for 6e728b67bd526bceb077c02231d2ec6f is:
I tried to dump $status into a variable and output to file, and the file said:
the current uid: 02e9a3e0214ffd731265ec5b0b220b4c
the current status: NULL
So basically, the status is consistently returning NULL. Why? This was (and still is) working fine in the demo, what could be going wrong while integrating it into my web app code? There's nothing wrong with the image uploading on its own - my images are getting uploaded fine, but the progress isn't getting tracked!
The form that gets created dynamically looks like this:
<div class="dialog-container">
<form id="imgform" method="post" enctype="multipart/form-data" action="upload_1-img.php" target="upload_target">
Select image:
<br>
<input id="image" type="file" name="image">
<div id="imgwrapper"></div>
<input id="filename" type="hidden" value="" name="filename">
<input id="upath" type="hidden" value="xxxxxxxxxxxxxxxxxxxxxxxxxx" name="upath">
<center>
<input id="imgupload" type="submit" onclick="showUploadedItem()" value="Upload">
<input id="clearcrop" type="button" disabled="disabled/" value="Clear selection">
<input id="imgapproved" type="button" disabled="disabled" value="Done">
<input id="imgcancel" type="button" value="Cancel">
</center>
</form>
</div>
<div id="progress-bar"><div id='inner'></div></div>
<!-- etc etc some other elements -->
</div>
and my own upload_1-img.php starts off with:
$filename = $_FILES["image"]["tmp_name"];
$file_info = new finfo(FILEINFO_MIME);
$bfr = $file_info->buffer(file_get_contents($filename)) or die ("error");
// some more stuff, getting file type and file's $name
if( /* a bunch of conditions */ )
move_uploaded_file( $_FILES["image"]["tmp_name"], $upath . "/" . $name);
Woohoo! I figured it out, thanks to this bug:
https://bugs.php.net/bug.php?id=57505
Basically, just I removed this static line from the page where users get to upload files:
<input type='hidden' name='UPLOAD_IDENTIFIER' id='uid' value='<?php echo md5(uniqid(mt_rand())); ?>' />
and in my javascript function that creates the image dialog dynamically, I just added the hidden input dynamically, right above the line where I generated the file input.
So the relevant part of the dynamically created form then looks like:
<input type='hidden' name='UPLOAD_IDENTIFIER' id='uid' value='1325a38f3355c0b1b4' />
<input id="image" type="file" name="image">
Now since this is getting dynamically created via javascript anyway, I can just replace that value above with a random js function.
Now the progress bar is advancing as it ought to! :D

Display Image's on same page from different folder using jquery

This code I get by search..
<html>
<head>
<title>Get url for address bar</title>
<script>
function display(folder,img_name)
{
var src = "http://localhost/UPLOADER/images/"+folder+"/"+img_name;
show_image("http://localhost/UPLOADER/images/"+folder+"/"+img_name, 276,110, "Img");
}
function show_image(src, width, height, alt)
{
var img = document.createElement("img");
img.src = src;
img.width = width;
img.height = height;
img.alt = alt;
document.body.appendChild(img);
}
</script>
</head>
<body>
<input type="text" name="image" value="" style="margin-top: 4px;" placeholder="Image_name" />
<button onclick="display('a','access')">DISPLAY IMAGE</button>
</body>
</html>
This code I take from site for jquery it worls well but I think I done some mistake in my code its not easy to grab the error as it display. undefined image and function display.
I want to add this for dynamic selection of image
<?php
$img_name=$_POST['image'];
$folder = substr($img_name, 0, 1);
?>
<button onclick="display('$folder','$img_name')">DISPLAY IMAGE</button>
for extension I use .htaccess Options +MultiViews
thanks
ok there are many many solutions to this problem, changing it to an ajax call to the php page to get the image/images would be one, a very simple solution would be this...
<?php
$image = (isset($_REQUEST['image'])) ? $_REQUEST['image'] : false;
$folder = ($image) ? substr($image, 0, 1) : false;
?>
<html>
<head>
<title>Get url for address bar</title>
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script>
var image = '<?php echo ($image) ? $image : "false"; ?>';
var folder = '<?php echo ($folder) ? $folder : "false"; ?>';
var extension = '.jpg';
function DISPLAY(folder,img_name, imgExt) {
var finalExt = (typeof imgExt != 'undefined') ? imgExt : extension;
if(img_name != 'false' && folder != 'false') {
show_image("http://localhost/UPLOADER/images/"+folder+"/"+img_name+finalExt, 276,110, "Img");
} else {
console.log("looks like something was undefined, here's the values:");
console.log(folder);
console.log(img_name);
}
}
function show_image(src, width, height, alt)
{
var img = document.createElement("img");
img.src = src;
img.width = width;
img.height = height;
img.alt = alt;
document.body.appendChild(img);
}
//if using jquery
$(document).ready(function() {
//you could also add logic here to see if values are not 'false' and run function
DISPLAY(folder, image);
});
</script>
</head>
<body>
<form action="" method="POST">
<input type="text" name="image" value="" style="margin-top: 4px;" placeholder="Image_name" />
<button>DISPLAY IMAGE</button>
</form>
</body>
</html>

PHP/JS script is not working inside HTML

I am adding an upload function to the HTML div, but for some reason it is not working. I have also created a php file with the same scripts I have added to the div and did the action="upload-page.php", but it does not get the php page either. What could be the problem?
Here is the code:
<div class="wall-ptype-cnt wall_text" >
__post_wall_text__
<form method="post" action="upload-page.php" enctype="multipart/form-data">
<input name="filesToUpload[]" id="filesToUpload" type="file" multiple="" />
<script language="javascript" type="text/javascript">
var input = document.getElementById('filesToUpload');
var list = document.getElementById('fileList');
while (list.hasChildNodes()) {
list.removeChild(ul.firstChild);
}
for (var x = 0; x < input.files.length; x++) {
var li = document.createElement('li');
li.innerHTML = 'File ' + (x + 1) + ': ' + input.files[x].name;
list.append(li);
}
</script>
<?php if(count($_FILES['uploads']['filesToUpload'])) {
foreach ($_FILES['uploads']['filesToUpload'] as $file) {
//do your upload stuff here
echo $file;
}
}
?>
</form>
</div>
Why does the php page is not being processed and why the script is not working as well?
The script I have in upload-page.php is the same I am putting inside html.
A couple of mistakes in your code:
"list.removeChild(ul.firstChild);" should be "list.removeChild(list.firstChild);"
"list.append(li);" should be "list.appendChild(li);"

File Upload Progress for Dynamic Dropdown File Upload

I have made a dynamic dropdown file upload system where user can choose the engineering stream, then the semester and then subject, and the file gets uploaded in the desired directory. This works fine normally. I came across the Javascript/AJAX File Upload Progress tutorial from PHPAcademy, things worked fine until I got stuck into this.
Without adding the javascript file (for upload progress), the files get uploaded in the correct directory, show no errors in the firebug, and also gives the link to the file after it gets uploaded.
But after I add the JS file, the link doesn't come after upload, it gets uploaded in the root directory always, it shows the progress though, and the console shows two errors.
Here is my PHP code:
<?php
if(isset($_POST['upload'])) {
$path1=$_POST['one']."/";
$path2=$_POST['two']."/";
$path3=$_POST['three']."/";
$upload_path=$path1.$path2.$path3;
}
else {
echo "Follow the instructions before uploading a file";
}
if(!empty($_FILES['file'])) {
foreach($_FILES['file']['name'] as $key => $name) {
if($_FILES['file']['error'][$key]==0 && move_uploaded_file($_FILES['file']['tmp_name'][$key], $upload_path."$name")) {
$uploaded[] = $name;
}
}
if(!empty($_POST['ajax'])) {
die(json_decode($uploaded));
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title> SRMUARD - Upload </title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript" src="upload.js"></script>
<script type="text/javascript">
function val()
{
if(document.uploads.three.selectedIndex == 0)
{
alert("Please choose all the appropriate options");
}
}
</script>
<script>
$(function() {
$("#text-one").change(function() {
$("#text-two").load("textdata/" + $(this).val() + ".txt");
});
$("#text-two").change(function() {
$("#text-three").load("textdata/" + $(this).val() + ".txt");
});
});
</script>
</head>
<body>
<div value="<?php $upload_path ?>" id="uploadpath"></div>
<div id="uploaded">
<?php
if(!empty($uploaded)) {
foreach($uploaded as $name) {
echo 'File Link: '.'<a href="' . $upload_path . $name . '" >', $name, '</a><br/>';
}
}
?>
</div>
<div id="upload_progress" style="display: none"></div>
<div>
<form action="" method="POST" enctype="multipart/form-data" name="upload" id="upload">
<label for="file">Choose a file: </label><br/>
<input type="file" name="file[]" id="file" multiple="multiple"><br/><br/>
<select id="text-one" name="one">
<option selected value="base">Select Department</option>
<option value="CSE" name="cse">Computer Science Engineering</option>
<option value="ECE" name="ece">Electronics & Communication Engineering</option>
<option value="MECH" name="mech">Mechanical Engineering</option>
</select><br/><br/>
<select id="text-two" name="two"> //Displays options dynamically using text files
<option>Select Semester</option>
</select><br/><br/>
<select id="text-three" name="three"> //Displays options dynamically using text files
<option>Select Subject</option>
</select><br/><br>
<input type="submit" name="upload" id="submit" value="Upload" onClick="val()" />
</form>
<div>
</body>
</html>
And here is my javascript code:
var handleUpload = function(event) {
event.preventDefault();
event.stopPropagation();
var fileInput = document.getElementById('file');
var data = new FormData();
data.append('ajax', true);
for(var i = 0; i < fileInput.files.length; ++i) {
data.append('file[]', fileInput.files[i]);
}
var request = new XMLHttpRequest();
request.upload.addEventListener('progress', function(event) {
if(event.lengthComputable) {
var percent = event.loaded / event.total;
var progress = document.getElementById('upload_progress');
while(progress.hasChildNodes()) {
progress.removeChild(progress.firstChild);
}
progress.appendChild(document.createTextNode(Math.round(percent * 100) + '%'));
}
});
request.upload.addEventListener('load', function(event) {
document.getElementById('upload_progress').style.display = 'none';
});
request.upload.addEventListener('error', function(event) {
alert('Upload failed due to some reason!');
});
request.addEventListener('readystatechange', function(event) {
if(this.readyState == 4) {
if(this.status == 200) {
var links = document.getElementById('uploaded');
var uploaded = eval(this.response);
var div, a;
var phpval = document.getElementById('uploadpath').value;
for(var i=0; i < uploaded.length; ++i) {
div = document.createElement('div');
a = document.createElement('a');
a.setAttribute('href', phpval + uploaded[i]);
a.appendChild(document.createTextNode(uploaded[i]));
div.appendChild(a);
links.appendChild(div);
}
} else {
console.log('Server replied with HTTP status ' + this.status);
}
}
});
request.open('POST','upload.php');
request.setRequestHeader('Cache-Control','no-cache');
document.getElementById('upload_progress').style.display = 'block';
request.send(data);
}
window.addEventListener('load',function(event) {
var submit = document.getElementById('submit');
submit.addEventListener('click', handleUpload);
});
And the errors shown in the console are:
TypeError: document.uploads is undefined
[Break On This Error]
if(document.uploads.three.selectedIndex == 0)
and
SyntaxError: missing ; before statement upload.js file line 47 which is var uploaded = eval(this.response);
And another place where I feel I am making a mistake is:
a.setAttribute('href', phpval + uploaded[i]);
The phpval must correspond to the dynamic upload link. I couldn't use the $upload_path in the JS, so made a div out of it, and then used to get the value like this:
var phpval = document.getElementById('uploadpath').value;
For the demo, you can refer this link, things will be more precise, please turn on your firebug console and check the errors and help me. I am not able to solve this.
Dynamic Dropdown File Upload with Progress Indication
Thank You
Also consider positioning of your script properly. Sometimes what happens is the place where you place your script might cause conflicts. I can see that you have the scripts for Dynamic Dropdown Functionality already. Try placing it after your form and check if it works.
Hope this helps.
There are many JQuery options you could try. Here is one from Blueimp. Hope this helps.

Categories