PHP return uploaded filename for verification - php

I just need someone to point me into a direction to do the following.
Once I successfully upload a file to /uploads on my server; the PHP iteratively changes the filename by adding a number if the same file exists (basic override protection). After the file is successfully uploaded, I need a PHP function that can return that filename AND THEN (this is the hard part) to the very page that triggered the PHP uploader script. I will then capture the filename as a variable and pass it to the next page via a cookie (this latter 2 things I already know how to do).
code PHP script:
<?php
$allowedExts = array("zip", "rar"/*, "bmp", "jpg", "png", "tiff"*/);
$temp = explode(".", $_FILES["file"]["name"]);
$name = pathinfo($_FILES["file"]["name"], PATHINFO_FILENAME);
$extension = pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION);
$i = '';
if ((($_FILES["file"]["type"] == "application/zip")
|| ($_FILES["file"]["type"] == "application/x-zip")
|| ($_FILES["file"]["type"] == "application/octet-stream")
|| ($_FILES["file"]["type"] == "application/x-zip-compressed")
|| ($_FILES["file"]["type"] == "application/x-rar-compressed")
/*|| ($_FILES["file"]["type"] == "image/bmp")
|| ($_FILES["file"]["type"] == "image/jpg")
|| ($_FILES["file"]["type"] == "image/png")
|| ($_FILES["file"]["type"] == "image/tiff")*/)
&& ($_FILES["file"]["size"] < 50000000)
&& in_array($extension, $allowedExts))
{
if ($_FILES["file"]["error"] > 0)
{
echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
} else
{
if (file_exists("upload/" . $name . $i . '.' . $extension))
{
while(file_exists("upload/" . $name . $i . '.' . $extension)) {
$i++;
}
$basename = $name . $i . '.' . $extension;
move_uploaded_file($_FILES["file"]["tmp_name"],
"upload/" . $basename);
} else
{
move_uploaded_file($_FILES["file"]["tmp_name"],
"upload/" . $_FILES["file"]["name"]);
}
}
} else
{
echo "Invalid file";
}
?>
HTML5 Upload:
<!DOCTYPE html>
<!-- saved from url=(0044)http://html5demos.com/dnd-upload#view-source -->
<html lang="en"><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta charset="utf-8">
<title>HTML5 Demo: Drag and drop, automatic upload</title>
<body>
<section id="wrapper">
<header>
<h4>Drag and drop</h4>
</header>
<style>
#holder { border: 1px dashed lightgrey; width: 300px; min-height: 300px; margin: 20px auto;}
#holder.hover { border: 1px dashed #FFCC00; }
#holder img { display: block; margin: 10px auto; }
#holder p { margin: 10px; font-size: 14px; }
progress { width: 50%; }
progress:after { content: ''; }
.fail { background: #c00; padding: 2px; color: #fff; }
.hidden { display: none !important;}
</style>
<article>
<div id="holder">
</div>
<p id="upload" class="hidden"><label>Drag & drop not supported, but you can still upload via this input field:<br><input type="file"></label></p>
<p id="filereader" class="hidden">File API & FileReader API not supported</p>
<p id="formdata" class="hidden">XHR2's FormData is not supported</p>
<p id="progress" class="hidden">XHR2's upload progress isn't supported</p>
<p>Upload progress: <progress id="uploadprogress" min="0" max="100" value="0">0</progress></p>
</article>
<script>
var holder = document.getElementById('holder'),
tests = {
filereader: typeof FileReader != 'undefined',
dnd: 'draggable' in document.createElement('span'),
formdata: !!window.FormData,
progress: "upload" in new XMLHttpRequest
},
support = {
filereader: document.getElementById('filereader'),
formdata: document.getElementById('formdata'),
progress: document.getElementById('progress')
},
acceptedTypes = {
//'image/bmp': true
//'image/jpg': true,
//'image/png': true,
},
progress = document.getElementById('uploadprogress'),
fileupload = document.getElementById('upload');
"filereader formdata progress".split(' ').forEach(function (api) {
if (tests[api] === false) {
support[api].className = 'fail';
} else {
// FFS. I could have done el.hidden = true, but IE doesn't support
// hidden, so I tried to create a polyfill that would extend the
// Element.prototype, but then IE10 doesn't even give me access
// to the Element object. Brilliant.
support[api].className = 'hidden';
}
});
function previewfile(file) {
/*if (tests.filereader === true && acceptedTypes[file.type] === true) {
var reader = new FileReader();
reader.onload = function (event) {
var image = new Image();
image.src = event.target.result;
image.width = 250; // a fake resize
holder.appendChild(image);
};
reader.readAsDataURL(file);
} else {*/
holder.innerHTML += '<p>Uploaded ' + file.name + ' ' + (file.size ? (file.size/1024|0) + 'K' : '');
console.log(file);
/*}*/
}
function readfiles(files) {
//debugger;
var formData = tests.formdata ? new FormData() : null;
for (var i = 0; i < files.length; i++) {
if (tests.formdata) formData.append('file', files[i]);
previewfile(files[i]);
}
// now post a new XHR request
if (tests.formdata) {
var xhr = new XMLHttpRequest();
xhr.open('POST', 'upload_artwork.php');
xhr.onload = function() {
progress.value = progress.innerHTML = 100;
};
if (tests.progress) {
xhr.upload.onprogress = function (event) {
if (event.lengthComputable) {
var complete = (event.loaded / event.total * 100 | 0);
progress.value = progress.innerHTML = complete;
}
}
}
xhr.send(formData);
}
}
if (tests.dnd) {
holder.ondragover = function () { this.className = 'hover'; return false; };
holder.ondragend = function () { this.className = ''; return false; };
holder.ondrop = function (e) {
this.className = '';
e.preventDefault();
readfiles(e.dataTransfer.files);
}
} else {
fileupload.className = 'hidden';
fileupload.querySelector('input').onchange = function () {
readfiles(this.files);
};
}
</script>
</body></html>

Submit the form with ajax form submit which will return the values of the file path . Hope this help's you..
<?php
if($_FILES["file"]["name"] != '')
{
$output_dir="uploads/";
if(move_uploaded_file($_FILES["file"]["tmp_name"],$output_dir.$_FILES["file"]["name"]))
{
chmod($output_dir.$_FILES["file"]["name"],0777);
echo $_FILES["file"]["name"];
exit;
}
}
?>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js"></script>
<script src="http://malsup.github.com/jquery.form.js"></script>
<script>
// wait for the DOM to be loaded
$(document).ready(function() {
var jvar="";
// bind 'myForm' and provide a simple callback function
$('#myForm').ajaxForm({
clearForm: 'true',
success: function(data){
if(data != '')
{
jvar=data;
window.location.href="test.php?path="+jvar;
//Assign the to a variable and pass to another file
}
}
});
});
</script>
</head>
<form id="myForm" action="test.php" method="post">
<input type="file" name="file">
<input type="submit" value="Submit Comment" />
</form>

Create two fields in database 1st name and 2nd server name to access it later
$name = $_FILES['file']['name'];
//Insert this in first field
//Insert it in server name field
$stored_name = $_FILES['file']['name'].rand(10, 50);
// name generated by you not automatically added if file already exists
move_uploaded_file($_FILES["file"]["tmp_name"], $stored_name);
Check out rand function here
http://php.net/manual/en/function.rand.php

Related

Create previous back button for image gallery. Images loaded from folder as array

I have images loaded from folder via PHP. Next button works with settimeout, when button is clicked jQuery hide image and show next image. How could i make previous button ?
Here is gallery link.
http://onlinegallery.online/index.php
Buttons are hidden at the right top after click > button at the bottom right on main page.
I tried to add this code below for previous button
but it shows some another image-div , not previous.
jQuery(".hidewinprev").on("click keyup", function (e) {
if (e.type == "click" || e.keyCode == 39) {
jQuery('#slideshow > div:first')
.fadeOut(500)
.prev()
.fadeIn(500)
.end()
.appendTo('#slideshow');
jQuery('#slideshow > div').css('display','none');
jQuery('#slideshow > div:first').css('display','flex');
}
});
//php scandir echo images
$list = scandir($dir);
foreach ($list as $file) {
if (is_file($dir . '/' . $file)) {
$ext = strtolower(pathinfo($file, PATHINFO_EXTENSION));
if ($ext == 'gif' || $ext == 'jpeg' || $ext == 'jpg' || $ext == 'png') {
echo "<div class='' data-title='" . basename($file,".$ext") . "'>\n<img src=\"" . $dir . '/' . $file . "\" alt=\"" . $dir . "\"><br />\n</div>\n";
}
}
}
//html output
<div><img></div>
<div><img></div>
....
//button next jquery works
jQuery(".hidewinnext").on("click keyup", function (e) {
if (e.type == "click" || e.keyCode == 39) {
jQuery('#slideshow > div:first')
.fadeOut(500)
.next()
.fadeIn(500)
.end()
.appendTo('#slideshow');
jQuery('#slideshow > div').css('display','none');
jQuery('#slideshow > div:first').css('display','flex');
}
});
[1]: https://i.stack.imgur.com/fMnln.jpg
Try with the following code:
HTML Code:
<div id="big-image">
<img src="http://lorempixel.com/400/200/sports/1/">
<img src="http://lorempixel.com/400/200/fashion/1/">
<img src="http://lorempixel.com/400/200/city/1/">
</div>
<div class="small-images">
<img class="selected" src="http://lorempixel.com/100/50/sports/1/">
<img src="http://lorempixel.com/100/50/fashion/1/">
<img src="http://lorempixel.com/100/50/city/1/">
</div>
<button id="prev">Prev</button>
<button id="next">Next</button>
JS Code:
$(function () {
$("#big-image img:eq(0)").nextAll().hide();
$(".small-images img").click(function (e) {
var $this = $(this),
index = $this.index();
$(".small-images img").removeClass('selected');
$this.addClass('selected');
$("#big-image img").eq(index).show().siblings().hide();
});
$('#next').click(function(){
var $selected = $('.selected');
var index = $selected.next('img').index();
if(index == -1){
index = 0;
}
var $curr = $(".small-images img").eq(index);
$(".small-images img").removeClass('selected');
$curr.addClass('selected');
$("#big-image img").eq(index).show().siblings().hide();
});
$('#prev').click(function(){
var $selected = $('.selected');
var index = $selected.prev('img').index();
var $curr = $(".small-images img").eq(index);
$(".small-images img").removeClass('selected');
$curr.addClass('selected');
$("#big-image img").eq(index).show().siblings().hide();
});
});
CSS Code:
.small-images a, .big-images a {
display:inline-block
}
.small-images .selected {
border:1px solid red
}
Here is the JSFiddle: http://jsfiddle.net/vb5pk408/

Upgrade PHP...then... error with file upload file

I'm not a php programmer. Someone ask me help for a web server with problem. I fix everything and update PHP 5.4 to 5.6. Everything work fine on his php program, except file upload.
Message: getimagesize(var/www/myserver/admin/uploads/temp/test.jpg): failed to open stream: No such file or directory
error on this line: $img_info = getimagesize("uploads/temp/$filename");
if($_POST['fileselect'][0] != "")
$filename=$_POST['fileselect'][0];
else
$filename=$_POST['dragfile'];
if(strlen($filename) > 3){
$finalname=time(); //Set a unique filename by the UNIX time
//Convert to jpg if tiff
$img_info = getimagesize("uploads/temp/$filename");
if($img_info['mime'] == "image/tiff"){
$clearname=explode(".", "$filename")[0];
system("convert uploads/temp/\"$filename\"[0] uploads/temp/$clearname.jpg");
unlink("uploads/temp/$filename");
$filename=$clearname.".jpg";
}
The problem probably come from a new code formulation in php5.6, any idea how to fix that ?
UPDATE 2: FILE UPLOAD section...
part of form.php
<form method="post" class="form-horizontal">
<input type="hidden" id="to_upload" name="to_upload" value="/upload.php">
<input type="hidden" id="MAX_FILE_SIZE" name="MAX_FILE_SIZE" value="300000000" />
<input type="hidden" id="id_produit" name="id_produit" value="<?php echo $this->mdl_inventory->form_value('idproduit'); ?>" />
<div class="control-group">
<label class="control-label">Nouveau (jpeg): </label>
<div class="controls">
<input type="file" id="fileselect" name="fileselect[]">
</div>
</div>
Does the name fileselect[] can be the problem ? How can i check if the script go in "upload.php" ?
part of upload.php
/* read the source image */
$source_image = imagecreatefromjpeg("$src");
$width = imagesx($source_image);
$height = imagesy($source_image);
$fn = (isset($_SERVER['HTTP_X_FILENAME']) ? $_SERVER['HTTP_X_FILENAME'] : false);
if ($fn) {
// AJAX call
file_put_contents(
'uploads/temp/' . $fn,
file_get_contents('php://input')
);
echo "$fn uploaded";
exit();
}else {
// form submit
$files = $_FILES['fileselect'];
foreach ($files['error'] as $id => $err) {
if ($err == UPLOAD_ERR_OK) {
$fn = $files['name'][$id];
move_uploaded_file(
$files['tmp_name'][$id],
'uploads/' . $fn
);
echo "<p>File $fn uploaded.</p>";
}
}
}
ajax script filedrag.js (upload)
(function() {
// getElementById
function $id(id) {
return document.getElementById(id);
}
// output information
function Output(msg) {
var m = $id("messages");
m.innerHTML = msg + m.innerHTML;
}
// file drag hover
function FileDragHover(e) {
e.stopPropagation();
e.preventDefault();
e.target.className = (e.type == "dragover" ? "hover" : "");
}
// file selection
function FileSelectHandler(e) {
// cancel event and hover styling
FileDragHover(e);
// fetch FileList object
var files = e.target.files || e.dataTransfer.files;
// process all File objects
for (var i = 0, f; f = files[i]; i++) {
ParseFile(f);
UploadFile(f);
}
}
// output file information
function ParseFile(file) {
Output(
"<p>File information: <strong>" + file.name +
"</strong> type: <strong>" + file.type +
"</strong> size: <strong>" + file.size +
"</strong> bytes</p>"
);
// display an image
if (file.type.indexOf("image") == 0) {
var reader = new FileReader();
reader.onload = function(e) {
Output(
"<p><strong>" + file.name + ":</strong><br />" +
'<img src="' + e.target.result + '" /></p>'
);
}
reader.readAsDataURL(file);
}
// display text
if (file.type.indexOf("text") == 0) {
var reader = new FileReader();
reader.onload = function(e) {
Output(
"<p><strong>" + file.name + ":</strong></p><pre>" +
e.target.result.replace(/</g, "<").replace(/>/g, ">") +
"</pre>"
);
}
reader.readAsText(file);
}
}
// upload JPEG files
function UploadFile(file) {
// following line is not necessary: prevents running on SitePoint servers
if (location.host.indexOf("sitepointstatic") >= 0) return
var xhr = new XMLHttpRequest();
if (xhr.upload && (file.type == "image/jpeg" || file.type == "image/tiff" ) && file.size <= $id("MAX_FILE_SIZE").value) {
// create progress bar
var o = $id("progress");
var progress = o.appendChild(document.createElement("p"));
progress.appendChild(document.createTextNode("upload " + file.name));
// progress bar
xhr.upload.addEventListener("progress", function(e) {
var pc = parseInt(100 - (e.loaded / e.total * 100));
progress.style.backgroundPosition = pc + "% 0";
}, false);
// file received/failed
xhr.onreadystatechange = function(e) {
if (xhr.readyState == 4) {
progress.className = (xhr.status == 200 ? "success" : "failure");
}
};
// start upload
xhr.open("POST", $id("to_upload").value + "?idproduit=" + $id("id_produit").value, true);
xhr.setRequestHeader("X_FILENAME", file.name);
xhr.send(file);
$('#dragfile').attr('value', file.name);
}
}
// initialize
function Init() {
var fileselect = $id("fileselect"),
filedrag = $id("filedrag"),
submitbutton = $id("submitbutton");
// file select
fileselect.addEventListener("change", FileSelectHandler, false);
// is XHR2 available?
var xhr = new XMLHttpRequest();
if (xhr.upload) {
// file drop
filedrag.addEventListener("dragover", FileDragHover, false);
filedrag.addEventListener("dragleave", FileDragHover, false);
filedrag.addEventListener("drop", FileSelectHandler, false);
filedrag.style.display = "block";
// remove submit button
//submitbutton.style.display = "none";
}
}
// call initialization file
if (window.File && window.FileList && window.FileReader) {
Init();
}
})();
The syntax for the code mentioned is correct for 5.6, no issues with that.
I don't see permissions as the issue as well, otherwise you'd have gotten a 'Permission denied' error.
So, most likely, it looks like, the file that you are looking for does not exist in the folder.
the error was here:
xhr.setRequestHeader("X_FILENAME", file.name);
X-filename... i think it's APACHE UPDATE problem.
Thanks for help.

unable to create thumb nail in php

Am using PHP to create thumbnail from following code but when i run code i get following ERROR
Notice: Undefined variable: phpThumb in C:\Users\logon\Documents\NetBeansProjects\rename multiple file with rename frm single input\for.php on line 42
Fatal error: Call to a member function setSourceFilename() on a non-object in C:\Users\logon\Documents\NetBeansProjects\rename multiple file with rename frm single input\for.php on line 42
since am uploading multiple file how do i create thumb for all formate images
PHP processing code for uploading multiple image and creating thumb
<?php
$newname = uniqid() . '_' . time();
$file1 = isset($_FILES['files']['name'][0]) ? $_FILES['files']['name'][0] : null;
$file2 = isset($_FILES['files']['name'][1]) ? $_FILES['files']['name'][1] : null;
$file3 = isset($_FILES['files']['name'][2]) ? $_FILES['files']['name'][2] : null;
$file4 = isset($_FILES['files']['name'][3]) ? $_FILES['files']['name'][3] : null;
$file5 = isset($_FILES['files']['name'][4]) ? $_FILES['files']['name'][4] : null;
if (isset($_FILES['files'])) {
$errors = array();
foreach ($_FILES['files']['tmp_name'] as $key => $tmp_name) {
$file_name = $key . $_FILES['files']['name'][$key];
$file_size = $_FILES['files']['size'][$key];
$file_tmp = $_FILES['files']['tmp_name'][$key];
$file_type = $_FILES['files']['type'][$key];
if ($file_size > 2097152) {
$errors[] = 'File size must be less than 2 MB';
}
$desired_dir = "user_data";
if (empty($errors) == true) {
if (is_dir($desired_dir) == false) {
mkdir("$desired_dir", 0700); // Create directory if it does not exist
}
if (is_dir("$desired_dir/" . $file_name) == false) {
move_uploaded_file($file_tmp, "$desired_dir/" . $newname . $file_name);
} else { // rename the file if another one exist
$new_dir = "$desired_dir/" . $newname . $file_name;
rename($file_tmp, $new_dir);
}
} else {
print_r($errors);
}
}
if (empty($error)) {
echo "FILE : $file1<br>";
echo "FILE : $file2<br>";
echo "FILE : $file3<br>";
echo "FILE : $file4<br>";
echo "FILE : $file5<br>";
//thumb creation
$files = array("$file1", "$file1", "$file1", "$file1", "$file1");
foreach ($files as $file) { // here's part 1 of your answer
$phpThumb->setSourceFilename($file);
$phpThumb->setParameter('w', 100);
$outputFilename = "thumbs/" . $file;
if ($phpThumb->GenerateThumbnail()) {
if ($phpThumb->RenderToFile($outputFilename)) { // here's part 2 of your answer
// do something on success
} else {
//failed
}
} else {
// failed
}
}
}
}
?>
Edited again to reflect the posters new wishes of how the user experience should be. Now has a drag-drop with preview OR manual selection of 5 files. The drag-drop is submitted by a ajax post, so watch the console for the result. Display and flow needs to be streamlined, but shows a technical working example. The same PHP code handles both results.
<html>
<body>
<pre><?
print_r($_FILES); //SHOW THE ARRAY
foreach ($_FILES as $file) {
if (!$file['error']) {
//PROCESS THE FILE HERE
echo $file['name'];
}
}
?></pre>
<script src="http://code.jquery.com/jquery-1.11.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
var fd = new FormData();
$(document).ready(function() {
//submit dragdropped by ajax
$("#dropsubmit").on("click", function(e) {
$.ajax({
data: fd,
processData: false,
contentType: false,
type: 'POST',
success: function(data){
//FILES POSTED OK! REDIRECT
console.log(data);
}
});
})
var dropzone = $("#dropzone");
dropzone.on('dragenter', function (e) {
$(this).css('background', 'lightgreen');
});
//dropped files, store as formdata
dropzone.on('dragover', stopPropagate);
dropzone.on('drop', function (e) {
stopPropagate(e)
$(this).css('background', 'white');
var files = e.originalEvent.dataTransfer.files;
for (var i = 0; i < files.length; i++) {
preview(files[i])
fd.append('file' + (i + 1), files[i]);
if (i >= 5) continue
}
});
function stopPropagate(e) {
e.stopPropagation();
e.preventDefault();
}
if (window.File && window.FileList && window.FileReader) {
$("input[type=file]").on("change", function(e) {
preview(e.target.files[0])
});
} else {
alert("Your browser doesn't support to File API")
}
function preview(item) {
var fileReader = new FileReader();
fileReader.onload = (function(e) {
var file = e.target;
$("<img></img>", {
class: "imageThumb",
src: file.result,
title: file.name,
}).appendTo("#images");
});
fileReader.readAsDataURL(item);
}
});
</script>
<div id="dropzone" style="width:100px;height:100px;border:2px dashed gray;padding:10px">Drag & Drop Files Here</div>
<input type="button" id="dropsubmit" value="Submit dropped files" />
<hr>
<form method="post" enctype="multipart/form-data">
<input id="file1" name="file1" type="file"/><br>
<input id="file2" name="file2" type="file"/><br>
<input id="file3" name="file3" type="file"/><br>
<input id="file4" name="file3" type="file"/><br>
<input id="file5" name="file3" type="file"/><br>
<input name="submit" type="submit" value="Upload files" />
</form><div id="images"></div>
</body>
</html>

Upload Progress when upload multiple files

I want to upload multi-file (more than 1000 files, with total more than 2GB).
In PHP, i use function
if (move_uploaded_file($_FILES['files']['tmp_name'][$i], $original_file))
{
$stamp = '../contents/wm_watermark.png';
$this->create_watermark_photo($original_file, $stamp, $view_file, $ext);
$this->makeThumbnail($view_file, $thumb_file, $this->max_width_thumb, $this->max_width_thumb);
//insert photo info to DB
$this->Photo->create();
$this->Photo->save(
array(
'Photo' => array(
'folder_id' => $data_from_preparing_fileInfoList[$i]['sub'],
'name' => $filename
)
)
);
$status = '1';
$count++;
}
I found out that, when use move_upload_file , it didn't upload right now. It only keep in waiting stack. When this function run completedly, then it move file to server.
So, when i use upload process, it gain 100% , this ajax url still run.
$("#image_upload_form").ajaxSubmit({
//url: '/admin/photoGroup/ajax_upload_photo', //photo upload process bar
type: 'POST',
dataType: 'json',
data: { data_from_preparing: data_from_preparing},
beforeSend: function() {
//dialog 1
$("#upload-photo-process .progress-bar").css('width', '0');
$('#upload-photo-process').modal('show');
},
/* progress bar call back*/
uploadProgress: function(event, position, total, percentComplete) {
console.log('percentComplete' + percentComplete);
console.log('position: ' + position);
console.log('total' + total);
var mbPosition = position / 1024 / 1024;
var mbTotal = total / 1024 / 1024;
var txtProcess = percentComplete + '% | ' + mbPosition + 'Mb/' + mbTotal + 'Mb';
var pVel = percentComplete + '%';
$("#upload-photo-process .process-status").html(txtProcess);
$("#upload-photo-process .progress-bar").css('width', pVel);
},
/* complete call back */
complete: function(xhr) {
if (xhr.statusText == "OK") {
$('#upload-photo-process').modal('hide');
$('#upload-done').modal('show');
}
}
/*success: function(data_from_photo_upload) {
}*/
});
Now, i want to when upload progress gain 100%, all of files uploaded to server.
How do i can that?
Thank in advanced.
try this it may work..
//attach
function sendFileToServer(formData, status, file) {
var uploadURL = "index.php?p=ticket-attach&ajax=1"; //Upload URL
var extraData = {}; //Extra Data.
var jqXHR = $.ajax({
xhr: function() {
var xhrobj = $.ajaxSettings.xhr();
if (xhrobj.upload) {
xhrobj.upload.addEventListener('progress', function(event) {
var percent = 0;
var position = event.loaded || event.position;
var total = event.total;
if (event.lengthComputable) {
percent = Math.ceil(position / total * 100);
}
//Set progress
status.setProgress(percent);
}, false);
}
return xhrobj;
},
url: uploadURL,
type: "POST",
contentType: false,
processData: false,
cache: false,
data: formData,
dataType: "json",
success: function(data) {
if (data['error'] == "") {
status.setProgress(100);
status.setFileNameSize(data['fname'].split(",")[0], file.size);
status.appendFN(data['fname']);
//var namef= ;
} else {
//alert(data['error']);
status.errorMsg();
}
}
});
status.setAbort(jqXHR);
}
function createStatusbar(obj) {
this.statusbar = $("<div class='statusbar' id=''></div>");
this.filename = $("<div class='filename'></div>").appendTo(this.statusbar);
this.size = $("<div class='filesize'></div>").appendTo(this.statusbar);
this.abort = $("<div class='abort'>×</div>").appendTo(this.statusbar);
this.progressBar = $("<div class='progressBar'><div></div></div>").appendTo(this.statusbar);
obj.append(this.statusbar);
this.setFileNameSize = function(name, size) {
var sizeStr = "";
var sizeKB = size / 1024;
if (parseInt(sizeKB) > 1024) {
var sizeMB = sizeKB / 1024;
sizeStr = sizeMB.toFixed(2) + " MB";
} else {
sizeStr = sizeKB.toFixed(2) + " KB";
}
this.filename.html(name);
this.size.html("(" + sizeStr + ")");
this.statusbar.attr("sizev", size);
$("#attach_size").attr("sizev", parseInt($("#attach_size").attr("sizev")) + size);
this.setTotalSize();
}
this.setTotalSize = function() {
//set total size
var size = parseInt($("#attach_size").attr("sizev"));
var sizeStr = "";
var sizeKB = size / 1024;
if (parseInt(sizeKB) > 1024) {
var sizeMB = sizeKB / 1024;
sizeStr = sizeMB.toFixed(2) + " MB";
} else {
sizeStr = sizeKB.toFixed(2) + " KB";
}
if (sizeStr != "" && size > 0) $("#attach_size").html("(" + sizeStr + ")");
else $("#attach_size").html("");
}
this.setProgress = function(progress) {
var progressBarWidth = progress * this.progressBar.width() / 100;
this.progressBar.find('div').animate({
width: progressBarWidth
}, 10).html(progress + "%");
if (parseInt(progress) >= 100) {
this.progressBar.hide();
if ($.isFunction(tinymce.get)) tinymce.get('mail_body').isNotDirty = 0;
$("#save_status").html("Not saved");
//this.abort.hide();
} else {
if ($.isFunction(tinymce.get)) tinymce.get('mail_body').isNotDirty = 1;
$("#save_status").html("Not saved");
}
}
this.setAbortFD = function() {
var sb = this.statusbar;
var ts = this;
this.abort.click(function() {
$.ajax({
type: "POST",
url: "index.php?p=ticket-dattach&ajax=1",
data: "fname=" + sb.children(".filename").children("input").val(),
//dataType: "json",
success: function(data) {
tinymce.get('mail_body').isNotDirty = 0;
$("#save_status").html("Not saved");
},
error: function() {
alert('File is not deleted');
}
});
//alert(sb.children(".filename").children("input").val());
$("#attach_size").attr("sizev", (parseInt($("#attach_size").attr("sizev")) - parseInt(sb.attr("sizev"))));
sb.remove();
ts.setTotalSize();
});
}
this.setAbort = function(jqxhr) {
var sb = this.statusbar;
var ts = this;
this.abort.click(function() {
jqxhr.abort();
if (sb.children(".progressBar").children("div").html() == "100%") {
$.ajax({
type: "POST",
url: "index.php?p=ticket-dattach&ajax=1",
data: "fname=" + sb.children(".filename").children("input").val(),
//dataType: "json",
success: function(data) {
tinymce.get('mail_body').isNotDirty = 0;
$("#save_status").html("Not saved");
},
error: function() {
alert('File is not deleted');
}
});
$("#attach_size").attr("sizev", (parseInt($("#attach_size").attr("sizev")) - parseInt(sb.attr("sizev"))));
sb.remove();
} else {
sb.remove();
}
ts.setTotalSize();
});
}
this.appendFN = function(fn) {
this.filename.append("<input type=\"hidden\" name=\"ticket_attach[]\" value=\"" + fn + "\" />");
}
this.errorMsg = function() {
var sb = this.statusbar;
sb.children(".progressBar").children("div").html("File Error");
sb.children(".progressBar").show();
sb.children(".filename").children("input").remove()
}
}
function toggle_class(clas) {
$("." + clas).toggle();
}
function insert_attach(input) {
var files = input.files;
$.each(files, function(idx, file) {
var fd = new FormData();
fd.append('ticket_attach', file);
var obj = $(".note-attachbox");
var status = new createStatusbar(obj); //Using this we can set progress.
status.setFileNameSize(file.name, file.size);
sendFileToServer(fd, status, file);
});
$("#afile_browser").val("");
}
.abort {
color: red;
cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div class="note-attachbox" id="attachbox" style="position: relative; display: inline;"></div>
<input type='file' id='afile_browser' onchange='return insert_attach(this);' style="opacity: 0; position: relative; display: inline; cursor: pointer; width: 100px; padding: 1px 0px; border: medium none;" multiple>
<div style="cursor: pointer; color: rgb(59, 179, 36); display: inline-block; font-weight: bold; font-size: 20px; vertical-align: middle; background: none; width: auto; padding: 5px 0px; margin-left: -105px;">+<i style="font-size: 15px; font-weight: normal;">Attach files<span id="attach_size" sizev="0"></span ></i>
</div>
Hello You can follow the below approach to get it done.
I have try my best to make the example as simple as possible.
You need to implement this approach in your code to reach the result.
The below code is working and tested.
Users
Contains user details username, password, email, profile_image and profile_image_small etc.
CREATE TABLE `users` (
`user_id` int(11) AUTO_INCREMENT PRIMARY KEY,
`username` varchar(255) UNIQUE KEY,
`password` varchar(100),
`email` varchar(255) UNIQUE KEY
)
User Uploads
Contains user upload details upload_id, image_name, user_id_fk(foreign key) and timestamp etc.
CREATE TABLE `user_uploads` (
`upload_id` int(11) AUTO_INCREMENT PRIMARY KEY,
`image_name` text,
`user_id_fk` int(11),
`created` int(11)
)
Javascript Code
$("#photoimg").live('change',function(){})- photoimg is the ID name of INPUT FILE tag and $('#imageform').ajaxForm() - imageform is the ID name of FORM. While changing INPUT it calls FORM submit without refreshing page using ajaxForm() method. Uploaded images will prepend inside #preview tag.
<script type="text/javascript" src="http://ajax.googleapis.com/
ajax/libs/jquery/1.8.1/jquery.min.js"></script>
<script type="text/javascript" src="jquery.wallform.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
$('#photoimg').live('change', function()
{
var A=$("#imageloadstatus");
var B=$("#imageloadbutton");
$("#imageform").ajaxForm({target: '#preview',
beforeSubmit:function(){
A.show();
B.hide();
},
success:function(){
A.hide();
B.show();
},
error:function(){
A.hide();
B.show();
} }).submit();
});
});
</script>
Here hiding and showing #imageloadstatus and #imageloadbutton based on form upload submit status.
index.php
Contains simple PHP and HTML code. Here $session_id=1 means user id session value.
<?php
include('db.php');
session_start();
$session_id='1'; // User login session value
?>
<div id='preview'>
</div>
<form id="imageform" method="post" enctype="multipart/form-data" action='ajaxImageUpload.php' style="clear:both">
Upload image:
<div id='imageloadstatus' style='display:none'><img src="loader.gif" alt="Uploading...."/></div>
<div id='imageloadbutton'>
<input type="file" name="photos[]" id="photoimg" multiple="true" />
</div>
</form>
ajaxImageUpload.php
Contains PHP code. This script helps you to upload images into uploads folder and it will rename image file into timestamp+session_id.extention format to avoid duplicates. This system will store image files into user_uploads with user session id tables
<?php
error_reporting(0);
session_start();
include('db.php');
$session_id='1'; //$session id
define ("MAX_SIZE","2000"); // 2MB MAX file size
function getExtension($str)
{
$i = strrpos($str,".");
if (!$i) { return ""; }
$l = strlen($str) - $i;
$ext = substr($str,$i+1,$l);
return $ext;
}
// Valid image formats
$valid_formats = array("jpg", "png", "gif", "bmp","jpeg");
if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST")
{
$uploaddir = "uploads/"; //Image upload directory
foreach ($_FILES['photos']['name'] as $name => $value)
{
$filename = stripslashes($_FILES['photos']['name'][$name]);
$size=filesize($_FILES['photos']['tmp_name'][$name]);
//Convert extension into a lower case format
$ext = getExtension($filename);
$ext = strtolower($ext);
//File extension check
if(in_array($ext,$valid_formats))
{
//File size check
if ($size < (MAX_SIZE*1024))
{
$image_name=time().$filename;
echo "<img src='".$uploaddir.$image_name."' class='imgList'>";
$newname=$uploaddir.$image_name;
//Moving file to uploads folder
if (move_uploaded_file($_FILES['photos']['tmp_name'][$name], $newname))
{
$time=time();
//Insert upload image files names into user_uploads table
mysql_query("INSERT INTO user_uploads(image_name,user_id_fk,created) VALUES('$image_name','$session_id','$time')");
}
else
{
echo '<span class="imgList">You have exceeded the size limit! so moving unsuccessful! </span>'; }
}
else
{
echo '<span class="imgList">You have exceeded the size limit!</span>';
}
}
else
{
echo '<span class="imgList">Unknown extension!</span>';
}
} //foreach end
}
?>
db.php
Database configuration file, just modify database credentials.
<?php
$mysql_hostname = "localhost";
$mysql_user = "username";
$mysql_password = "password";
$mysql_database = "database";
$prefix = "";
$bd = mysql_connect($mysql_hostname, $mysql_user, $mysql_password) or die("Opps some thing went wrong");
mysql_select_db($mysql_database, $bd) or die("Opps some thing went wrong");
?>
CSS
Style for image blocks.
#preview
{
color:#cc0000;
font-size:12px
}
.imgList
{
max-height:150px;
margin-left:5px;
border:1px solid #dedede;
padding:4px;
float:left;
}

How to handle multiple file upload using PHP

I want to upload files using PHP but the problem is that I don't know how many files I will upload.
My question is how can I upload files if I use file[]?
<form action="upload.php" method="post" enctype="multipart/form-data">
<label for="file">Filename:</label><input type="file" name="file[]" id="file" />
<br />
<label for="file">Filename:</label><input type="file" name="file[]" id="file" />
<br />
<input type="submit" name="submit" value="Submit" />
</form>
I will add just File box and I will use JavaScript to create more file input to upload but how to handle them in PHP?
See: $_FILES, Handling file uploads
<?php
if(isset($_FILES['file']['tmp_name']))
{
// Number of uploaded files
$num_files = count($_FILES['file']['tmp_name']);
/** loop through the array of files ***/
for($i=0; $i < $num_files;$i++)
{
// check if there is a file in the array
if(!is_uploaded_file($_FILES['file']['tmp_name'][$i]))
{
$messages[] = 'No file uploaded';
}
else
{
// copy the file to the specified dir
if(#copy($_FILES['file']['tmp_name'][$i],$upload_dir.'/'.$_FILES['file']['name'][$i]))
{
/*** give praise and thanks to the php gods ***/
$messages[] = $_FILES['file']['name'][$i].' uploaded';
}
else
{
/*** an error message ***/
$messages[] = 'Uploading '.$_FILES['file']['name'][$i].' Failed';
}
}
}
}
?>
This is a preferred method of mine. It includes a mysql insert to keep a table on the images uploaded. It also moves the image to the admin image folder and copies the image to the user sites image folder.
<?php
if(isset($_FILES['image']['tmp_name']))
{
$num_files = count($_FILES['image']['tmp_name']);
for($x =0; $x< $num_files;$x++){
$image = $_FILES['image']['name'][$x];
if(!is_uploaded_file($_FILES['image']['tmp_name'][$x]))
{
$messages[] = $image.' No file uploaded."<br>"';
}
if (move_uploaded_file($_FILES["image"]["tmp_name"][$x],"images/". $image)){
$messages[] = $image .' uploaded';
}
copy("images/".$image, '../images/'.$image);
mysql_query("INSERT INTO $table_name VALUES ('NULL','$id','images/$image')");
}
}
?>
<?php /*insert this into the form*/
$count= count($messages); for ($i =0; $i < $count; $i++){echo $messages[$i]."<br>";}
?>
Try this:
if(isset($_FILES['image_file'])) {
$file = $_FILES['image_file'];
for($i = 0; $i < count($file['name']); $i++){
$image = array(
'name' => $file['name'][$i],
'type' => $file['type'][$i],
'size' => $file['size'][$i],
'tmp_name' => $file['tmp_name'][$i],
'error' => $file['error'][$i]
);
// Here is your code to handle one file
}
In your code, just use '$image' instead of '$_FILES' ...
Ajax js
(function(){
var d = document, w = window;
/**
* Get element by id
*/
function get(element){
if (typeof element == "string")
element = d.getElementById(element);
return element;
}
/**
* Attaches event to a dom element
*/
function addEvent(el, type, fn){
if (w.addEventListener){
el.addEventListener(type, fn, false);
} else if (w.attachEvent){
var f = function(){
fn.call(el, w.event);
};
el.attachEvent('on' + type, f)
}
}
/**
* Creates and returns element from html chunk
*/
var toElement = function(){
var div = d.createElement('div');
return function(html){
div.innerHTML = html;
var el = div.childNodes[0];
div.removeChild(el);
return el;
}
}();
function hasClass(ele,cls){
return ele.className.match(new RegExp('(\\s|^)'+cls+'(\\s|$)'));
}
function addClass(ele,cls) {
if (!hasClass(ele,cls)) ele.className += " "+cls;
}
function removeClass(ele,cls) {
var reg = new RegExp('(\\s|^)'+cls+'(\\s|$)');
ele.className=ele.className.replace(reg,' ');
}
if (document.documentElement["getBoundingClientRect"]){
var getOffset = function(el){
var box = el.getBoundingClientRect(),
doc = el.ownerDocument,
body = doc.body,
docElem = doc.documentElement,
// for ie
clientTop = docElem.clientTop || body.clientTop || 0,
clientLeft = docElem.clientLeft || body.clientLeft || 0,
// In Internet Explorer 7 getBoundingClientRect property is treated as physical,
// while others are logical. Make all logical, like in IE8.
zoom = 1;
if (body.getBoundingClientRect) {
var bound = body.getBoundingClientRect();
zoom = (bound.right - bound.left)/body.clientWidth;
}
if (zoom > 1){
clientTop = 0;
clientLeft = 0;
}
var top = box.top/zoom + (window.pageYOffset || docElem && docElem.scrollTop/zoom || body.scrollTop/zoom) - clientTop,
left = box.left/zoom + (window.pageXOffset|| docElem && docElem.scrollLeft/zoom || body.scrollLeft/zoom) - clientLeft;
return {
top: top,
left: left
};
}
} else {
// Get offset adding all offsets
var getOffset = function(el){
if (w.jQuery){
return jQuery(el).offset();
}
var top = 0, left = 0;
do {
top += el.offsetTop || 0;
left += el.offsetLeft || 0;
}
while (el = el.offsetParent);
return {
left: left,
top: top
};
}
}
function getBox(el){
var left, right, top, bottom;
var offset = getOffset(el);
left = offset.left;
top = offset.top;
right = left + el.offsetWidth;
bottom = top + el.offsetHeight;
return {
left: left,
right: right,
top: top,
bottom: bottom
};
}
/**
* Crossbrowser mouse coordinates
*/
function getMouseCoords(e){
if (!e.pageX && e.clientX){
// In Internet Explorer 7 some properties (mouse coordinates) are treated as physical,
// while others are logical (offset).
var zoom = 1;
var body = document.body;
if (body.getBoundingClientRect) {
var bound = body.getBoundingClientRect();
zoom = (bound.right - bound.left)/body.clientWidth;
}
return {
x: e.clientX / zoom + d.body.scrollLeft + d.documentElement.scrollLeft,
y: e.clientY / zoom + d.body.scrollTop + d.documentElement.scrollTop
};
}
return {
x: e.pageX,
y: e.pageY
};
}
/**
* Function generates unique id
*/
var getUID = function(){
var id = 0;
return function(){
return 'ValumsAjaxUpload' + id++;
}
}();
function fileFromPath(file){
return file.replace(/.*(\/|\\)/, "");
}
function getExt(file){
return (/[.]/.exec(file)) ? /[^.]+$/.exec(file.toLowerCase()) : '';
}
// Please use AjaxUpload , Ajax_upload will be removed in the next version
Ajax_upload = AjaxUpload = function(button, options){
if (button.jquery){
// jquery object was passed
button = button[0];
} else if (typeof button == "string" && /^#.*/.test(button)){
button = button.slice(1);
}
button = get(button);
this._input = null;
this._button = button;
this._disabled = false;
this._submitting = false;
// Variable changes to true if the button was clicked
// 3 seconds ago (requred to fix Safari on Mac error)
this._justClicked = false;
this._parentDialog = d.body;
if (window.jQuery && jQuery.ui && jQuery.ui.dialog){
var parentDialog = jQuery(this._button).parents('.ui-dialog');
if (parentDialog.length){
this._parentDialog = parentDialog[0];
}
}
this._settings = {
// Location of the server-side upload script
action: 'upload.php',
// File upload name
name: 'userfile',
// Additional data to send
data: {},
// Submit file as soon as it's selected
autoSubmit: true,
// The type of data that you're expecting back from the server.
// Html and xml are detected automatically.
// Only useful when you are using json data as a response.
// Set to "json" in that case.
responseType: false,
// When user selects a file, useful with autoSubmit disabled
onChange: function(file, extension){},
// Callback to fire before file is uploaded
// You can return false to cancel upload
onSubmit: function(file, extension){},
// Fired when file upload is completed
// WARNING! DO NOT USE "FALSE" STRING AS A RESPONSE!
onComplete: function(file, response) {}
};
// Merge the users options with our defaults
for (var i in options) {
this._settings[i] = options[i];
}
this._createInput();
this._rerouteClicks();
}
// assigning methods to our class
AjaxUpload.prototype = {
setData : function(data){
this._settings.data = data;
},
disable : function(){
this._disabled = true;
},
enable : function(){
this._disabled = false;
},
// removes ajaxupload
destroy : function(){
if(this._input){
if(this._input.parentNode){
this._input.parentNode.removeChild(this._input);
}
this._input = null;
}
},
/**
* Creates invisible file input above the button
*/
_createInput : function(){
var self = this;
var input = d.createElement("input");
input.setAttribute('type', 'file');
input.setAttribute('name', this._settings.name);
var styles = {
'position' : 'absolute'
,'margin': '-5px 0 0 -175px'
,'padding': 0
,'width': '220px'
,'height': '30px'
,'fontSize': '14px'
,'opacity': 0
,'cursor': 'pointer'
,'display' : 'none'
,'zIndex' : 2147483583 //Max zIndex supported by Opera 9.0-9.2x
// Strange, I expected 2147483647
};
for (var i in styles){
input.style[i] = styles[i];
}
// Make sure that element opacity exists
// (IE uses filter instead)
if ( ! (input.style.opacity === "0")){
input.style.filter = "alpha(opacity=0)";
}
this._parentDialog.appendChild(input);
addEvent(input, 'change', function(){
// get filename from input
var file = fileFromPath(this.value);
if(self._settings.onChange.call(self, file, getExt(file)) == false ){
return;
}
// Submit form when value is changed
if (self._settings.autoSubmit){
self.submit();
}
});
// Fixing problem with Safari
// The problem is that if you leave input before the file select dialog opens
// it does not upload the file.
// As dialog opens slowly (it is a sheet dialog which takes some time to open)
// there is some time while you can leave the button.
// So we should not change display to none immediately
addEvent(input, 'click', function(){
self.justClicked = true;
setTimeout(function(){
// we will wait 3 seconds for dialog to open
self.justClicked = false;
}, 3000);
});
this._input = input;
},
_rerouteClicks : function (){
var self = this;
// IE displays 'access denied' error when using this method
// other browsers just ignore click()
// addEvent(this._button, 'click', function(e){
// self._input.click();
// });
var box, dialogOffset = {top:0, left:0}, over = false;
addEvent(self._button, 'mouseover', function(e){
if (!self._input || over) return;
over = true;
box = getBox(self._button);
if (self._parentDialog != d.body){
dialogOffset = getOffset(self._parentDialog);
}
});
// we can't use mouseout on the button,
// because invisible input is over it
addEvent(document, 'mousemove', function(e){
var input = self._input;
if (!input || !over) return;
if (self._disabled){
removeClass(self._button, 'hover');
input.style.display = 'none';
return;
}
var c = getMouseCoords(e);
if ((c.x >= box.left) && (c.x <= box.right) &&
(c.y >= box.top) && (c.y <= box.bottom)){
input.style.top = c.y - dialogOffset.top + 'px';
input.style.left = c.x - dialogOffset.left + 'px';
input.style.display = 'block';
addClass(self._button, 'hover');
} else {
// mouse left the button
over = false;
if (!self.justClicked){
input.style.display = 'none';
}
removeClass(self._button, 'hover');
}
});
},
/**
* Creates iframe with unique name
*/
_createIframe : function(){
// unique name
// We cannot use getTime, because it sometimes return
// same value in safari :(
var id = getUID();
var iframe = toElement('<iframe src="javascript:false;" name="' + id + '" />');
iframe.id = id;
iframe.style.display = 'none';
d.body.appendChild(iframe);
return iframe;
},
/**
* Upload file without refreshing the page
*/
submit : function(){
var self = this, settings = this._settings;
if (this._input.value === ''){
// there is no file
return;
}
// get filename from input
var file = fileFromPath(this._input.value);
// execute user event
if (! (settings.onSubmit.call(this, file, getExt(file)) == false)) {
// Create new iframe for this submission
var iframe = this._createIframe();
// Do not submit if user function returns false
var form = this._createForm(iframe);
form.appendChild(this._input);
form.submit();
d.body.removeChild(form);
form = null;
this._input = null;
// create new input
this._createInput();
var toDeleteFlag = false;
addEvent(iframe, 'load', function(e){
if (// For Safari
iframe.src == "javascript:'%3Chtml%3E%3C/html%3E';" ||
// For FF, IE
iframe.src == "javascript:'<html></html>';"){
// First time around, do not delete.
if( toDeleteFlag ){
// Fix busy state in FF3
setTimeout( function() {
d.body.removeChild(iframe);
}, 0);
}
return;
}
var doc = iframe.contentDocument ? iframe.contentDocument : frames[iframe.id].document;
// fixing Opera 9.26
if (doc.readyState && doc.readyState != 'complete'){
// Opera fires load event multiple times
// Even when the DOM is not ready yet
// this fix should not affect other browsers
return;
}
// fixing Opera 9.64
if (doc.body && doc.body.innerHTML == "false"){
// In Opera 9.64 event was fired second time
// when body.innerHTML changed from false
// to server response approx. after 1 sec
return;
}
var response;
if (doc.XMLDocument){
// response is a xml document IE property
response = doc.XMLDocument;
} else if (doc.body){
// response is html document or plain text
response = doc.body.innerHTML;
if (settings.responseType && settings.responseType.toLowerCase() == 'json'){
// If the document was sent as 'application/javascript' or
// 'text/javascript', then the browser wraps the text in a <pre>
// tag and performs html encoding on the contents. In this case,
// we need to pull the original text content from the text node's
// nodeValue property to retrieve the unmangled content.
// Note that IE6 only understands text/html
if (doc.body.firstChild && doc.body.firstChild.nodeName.toUpperCase() == 'PRE'){
response = doc.body.firstChild.firstChild.nodeValue;
}
if (response) {
response = window["eval"]("(" + response + ")");
} else {
response = {};
}
}
} else {
// response is a xml document
var response = doc;
}
settings.onComplete.call(self, file, response);
// Reload blank page, so that reloading main page
// does not re-submit the post. Also, remember to
// delete the frame
toDeleteFlag = true;
// Fix IE mixed content issue
iframe.src = "javascript:'<html></html>';";
});
} else {
// clear input to allow user to select same file
// Doesn't work in IE6
// this._input.value = '';
d.body.removeChild(this._input);
this._input = null;
// create new input
this._createInput();
}
},
/**
* Creates form, that will be submitted to iframe
*/
_createForm : function(iframe){
var settings = this._settings;
// method, enctype must be specified here
// because changing this attr on the fly is not allowed in IE 6/7
var form = toElement('<form method="post" enctype="multipart/form-data"></form>');
form.style.display = 'none';
form.action = settings.action;
form.target = iframe.name;
d.body.appendChild(form);
// Create hidden input element for each data key
for (var prop in settings.data){
var el = d.createElement("input");
el.type = 'hidden';
el.name = prop;
el.value = settings.data[prop];
form.appendChild(el);
}
return form;
}
};
})();
jquery code for uploading
$(document).ready(function () {
var btnUpload=$('#browse');
$("#hidauto").css('display','block');
new AjaxUpload(btnUpload, {
action: '<?=site_url('brand/upload_image1/')?>',
name: 'file',
onSubmit: function(file, ext){$("#loadgif1").css("display","block");
if (! (ext && /^(jpg|jpeg|gif|png)$/.test(ext))){
// extension is not allowed
//document.getElementById("loadgif").style.display='block';
$("#loadgif1").css("display","none");
$("#image").css("display","block");
$("#image").html("only jpg,jpeg,png, images are allowed");
return false;
}
},
onComplete: function(file, response){
//alert(response);
if(response=='0'){
$("#primimage1_error").html("This image is too small please upload a bigger one");
$("#loadgif1").css("display","none");
return false;
}
$("#hidauto").css('display','block');
$("#loadgif1").css("display","none");
$("#image").html("");
var r=response;
//document.getElementById("imghid").value=response;
divid=r.replace(new RegExp(".jpg", 'g'),'');
divid=divid.replace(new RegExp(".jpeg", 'g'),'');
divid=divid.replace(new RegExp(".png", 'g'),'');
//alert(divid);
document.getElementById("imghidall").value=document.getElementById("imghidall").value+response+",";
shw='<div style="float: left; height:135px; width:147px;" id='+divid+'><img src="<?php echo base_url();?>uploads/'+response+'" width="125px" height="115px" /><div style="width: 125px;"><input type="radio" name="checkPrimary" title="Set as Primary image" value="'+divid+'" onClick="primaryimg('+"'"+r+"'"+');" style="margin:5px"><img src="<?php echo base_url();?>images/img_delete.png" width="17px" height="17px" title="delete" onClick="delete_image('+"'"+r+"'"+');" width="15px;" height="15px" style="float:right; margin-top:3px;"></div></div>';
// shw='<div style="float: left; height:135px; width:147px;" id='+divid+'><img src="<?php echo base_url();?>uploads/'+response+'" width="125px" height="115px" /><div style="width: 125px;"><input type="checkbox" id="checkPrimary" value="'+divid+'" onClick="primaryimg('+"'"+r+"'"+');" style="margin:5px"><img src="<?php echo base_url();?>images/remove.png" title="delete" onClick="delete_image('+"'"+r+"'"+');" width="15px;" height="15px" style="float:right; margin-top:2px;"></div></div>';
//alert(shw);
$("#hidauto").append( shw );
$("#primimage1_error").html("");
//location.reload();
}
});
});
HTML Code
<div class="r8_prt" style="margin-right: 0px; margin-top: 10px;">
<div class="line1">
<label style="float: left; width: 121px; margin-right:10%;">Upload images : </label><input type="file" name="browse" id="browse" multiple="true" style="float: left;">
<label class="error" for="dwn" id="allimg_error" style="display:block; color: #B94A48;font-size: 11px;font-weight: bold; text-align:center;" ></label>
<label class="error" for="dwn" id="primimage1_error" style="display:block; color: #B94A48;font-size: 11px;font-weight: bold; text-align:center;" ></label>
<label id="loadgif1" style="display:none; width:10px; float:left"><img style="margin-top:-10px" src="<?php echo base_url();?>images/ajax-loader(2).gif"></label>
<div id="image" style="float:left; width:110%; margin-top:20px; color:#F00;">
</div>
<div id="hidauto">
</div>
<input type="hidden" value="" id="imghid" name="imghid">
<input type="hidden" value="" id="imghidall" name="imghidall">
</div>
</div>
Upload function(For Codeigniter)
function upload_image1() {
$ext=$_FILES['file']['name'];
$epld=explode('.',$ext);
$nn= count($epld);$nn-=1;
$photo=date("MdyHis").".".$epld[$nn];
$data = getimagesize($_FILES['file']['tmp_name']);
$width = $data[0];
$height = $data[1]; if($width<250 || $height<250){ echo 0; die(); }
if( move_uploaded_file($_FILES['file']['tmp_name'],"./uploads/".$photo)){
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '15360'; //15MB
$config['max_width'] = '0';//'2000'
$config['max_height'] = '0';//'2000'
$config['min_width'] = '250';//'2000'
$config['min_height'] = '250';//'2000'
$this->load->library('upload', $config);
echo $photo;
} }
Delete Image
function delete_image(name)
{
var answer = confirm ("Do you want to delete this image?")
if (!answer)
{
}
else{
var base_url="<?php echo base_url();?>";
$.ajax
({
type: "POST",
url: base_url+"index.php/brand/delete_image/?imgname="+name,
data:'',
success: function(view)
{
name=name+",";
allname=document.getElementById("imghidall").value;
e=document.getElementById("imghidall").value = allname.replace(new RegExp(name, 'g'),'');
divid=name.replace(new RegExp(".jpg,", 'g'),'');
divid=divid.replace(new RegExp(".jpeg,", 'g'),'');
divid=divid.replace(new RegExp(".png,", 'g'),'');
//alert(divid);
document.getElementById(divid).innerHTML="";
$("#"+divid).css('width','0px');
}
});
}
}
Delete image function
function delete_image(){
$file_name=$_GET['imgname'];
unlink(FCPATH . '/uploads/' . $file_name);
unlink(FCPATH . '/uploads/thumb/' . $file_name);
unlink(FCPATH . '/uploads/watermark/' . $file_name);
}
if (isset($_FILES['file']['tmp_name'])) {
for ($i = 0; $i < count($_FILES['file']['tmp_name']); $i++) {
$tmpFilePath = $_FILES['file']['tmp_name'][$i];
if ($tmpFilePath != "") {
//. time() . $_FILES['file']['name'][$i] becomes the name of the files
$file[$i] = $newFilePath = "upload/myfolder/" . time() . $_FILES['file']['name'][$i];
if (move_uploaded_file($tmpFilePath, $newFilePath)) {
$file[$i] = $newFilePath = "upload/myfolder/" . time() . $_FILES['file']['name'][$i];
}
}
}
}
PUT THIS SIMPLE SCRIPT INTO PHP SCRIPT OR FUNCTION. NB:
$_FILES['file']
because <input type="file" name="file[]" id="file" />

Categories