I have on my website upload.php file please I want to use this script on my server which controls the upload of files to the server and can only upload one file.
Now I would like to do a multiple file upload with a drop zone just like here:
Multiple file Upload
As far as I know, I can set up a javascript and html form, but I don't know how to modify my upload.php file, which controls the upload of files to the server. Please see below is my upload.php file that controls the upload of one file how to modify it so that multiple files can be uploaded at once with the script whose link I left above:
<?php
$error_message = "";
$success_message = "";
if (IS_POST()) {
if ($_FILES['upload']) {
$name = $_FILES['upload']['name'];
$size = $_FILES['upload']['size'];
$type = getFileTypeText($_FILES['upload']['type']);
$ext = pathinfo($_FILES['upload']['name'], PATHINFO_EXTENSION);
$user = getUserFromSession();
$userId = $user->id;
if (!file_exists(ABSPATH . '/content/uploads/'.$userId.'/'.$name)) {
$acceptedExt = ['srt', 'ass', 'sub', 'sbv', 'vtt', 'stl'];
if (in_array($ext, $acceptedExt)) {
$db_name = GET_GUID() . "." . $ext;
$file_name_db = ABSPATH . '/content/uploads/' . $userId . '/' . $name;
$description = isset($_POST["description"]) && $_POST["description"] != '' ? $_POST["description"] : $name;
if ($size > 0) {
move_uploaded_file($_FILES['upload']['tmp_name'], $file_name_db);
chmod($file_name_db, 0666);
$id = db_insertUploadDetails($name, $description, $size, $userId, $ext, $name);
if ($id > 0) {
$success_message = "Uploaded successfully.";
echo "<script>location.href='list.php';</script>";
}
} else {
$error_message = "Not a valid file.";
}
} else {
$error_message = "Please upload only srt, ass, sub, sbv, vtt, stl";
}
}else{
$error_message="File Already Exists";
}
}
}
So your point is like ,you want to upload multiple files in series right.Use ajax to send it one after another and this will work.No need of any edits.
<!DOCTYPE html>
<html>
<head>
<title>Drag and drop Multiple files</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
<div class="container">
<h3>Drag and drop multiple file upload </h3><br />
<div id="drop_file_area">
Drag and Drop Files Here
</div>
<div id="uploaded_file"></div>
</div>
</body>
</html>
Use some css to tidy up the things.
ajax will be like this
<script>
$(document).ready(function () {
$("html").on("dragover", function (e) {
e.preventDefault();
e.stopPropagation();
});
$("html").on("drop", function (e) {
e.preventDefault();
e.stopPropagation();
});
$('#drop_file_area').on('dragover', function () {
$(this).addClass('drag_over');
return false;
});
$('#drop_file_area').on('dragleave', function () {
$(this).removeClass('drag_over');
return false;
});
$('#drop_file_area').on('drop', function (e) {
e.preventDefault();
$(this).removeClass('drag_over');
var formData = new FormData();
var files = e.originalEvent.dataTransfer.files;
for (var i = 0; i < files.length; i++) {
formData.append('file[]', files[i]);
}
uploadFormData(formData);
});
function uploadFormData(form_data) {
$.ajax({
url: "upload.php",
method: "POST",
data: form_data,
contentType: false,
cache: false,
processData: false,
success: function (data) {
$('#uploaded_file').append(data);
}
});
}
});
</script>
this will be the upload.php .db_config will be your db connect file
<?php
// Include the database connection file
include('db_config.php');
$fileData = '';
if(isset($_FILES['file']['name'][0]))
{
foreach($_FILES['file']['name'] as $keys => $values)
{
$fileName = $_FILES['file']['name'][$keys];
if(move_uploaded_file($_FILES['file']['tmp_name'][$keys], 'uploads/' . $values))
{
$fileData .= '<img src="uploads/'.$values.'" class="thumbnail" />';
$query = "INSERT INTO uploads (file_name, upload_time)VALUES('".$fileName."','".date("Y-m-d H:i:s")."')";
mysqli_query($con, $query);
}
}
}
echo $fileData;
?>
sanitizing the data is upto you.This is just an example
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.
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>
So I am working on this project where I have to make a photo sharing site, I select the photos and then upload them, send the link via email, and then the person goes on the link and downloads the photos. Everything works great when I have few photos and when not exceeding 100MB of data, when I go beyond that everything becomes unstable.
First of I am using HTML5's FileReader().The logic is the following:
I use FileReader() to transform each photo into a base64 code and every 3 photos transformed I send a 3 photos long base64 string via Ajax to a php file which then transforms the code into photos and uploads them into a folder on the server.
If I have 300 photos selected I do 100 ajax requests.
The first problem if if I exceed ~150MB of data ajax will give me an uncaught exception out of memory error.
The second problem is if I chose over 20-30 files the brower some times gets unresponsive even crashes..
Any suggestions what can I do ? Maybe the whole idea is wrong and I should start somewhere else, please help.
This is the code:
//Forming the inputs
$(document).on("change","#fileUp",function(e){
var file = null;
var files = e.target.files; //FileList object
var picReader = new FileReader();
$(".eventPop").html("");
$(".howMany").html("");
$(".eventPop").show();
$(".eventPop").append('<div class="adding"><img src="../public/cuts/uploading.gif" width="60px"></div>');
countUp = parseInt(countUp) + parseInt(files.length);
for(var i=0; i<=files.length-1; i++){
file = files[i];
var str = file.name.split(".")[0];
//
//var picReader = new FileReader();
if (file.type == "image/jpeg" || file.type == "image/png")
{
picReader.addEventListener("load",function(event){
count++;
var picFile = event.target;
$(".photos").append("<input type='hidden' id='ph"+count+"' get='"+picFile.result+"' /> ");
});
}
else
{
countUp--;
}
picReader.readAsDataURL(file);
}
});
//actual ajax requests
$(document).on('click','.uploadImages',function(){
info[1] = "4hold"+1 + Math.floor(Math.random() * 999999)+"_"+(new Date).getTime();
$.ajax({
type: "POST",
url: "index/loadIntoDB",
dataType:"text",
data: {info: info},
contentType: "application/x-www-form-urlencoded;charset=UTF-8",
success: function(result){
}
});
if (nrConfig > count)
{
nrConfig = count;
}
$(".eventPop").show();
$(".eventPop").html("");
$(".eventPop").append('<div class="adding"><p>Uploading files...'+( (nrConfig/count) * 100).toFixed(0)+'%</p></div>');
for(var i=1; i<=parseInt(nrConfig)+1; i++)
{
if (i == parseInt(nrConfig)+1)
{
info[2] = info[2].substring(2, info[2].length);
uploadImages(nrConfig,1);
}
else
{
//info[0] = i+"-"+info[0];
info[2] = info[2]+"--"+$("#ph"+i+"").attr("get");
}
}
});
function uploadImages(i,d){
info['3'] = i;
info['4'] = d;
$.ajax({
type: "POST",
url: "index/receiveImages",
dataType:"json",
data: {info : info },
beforeSend : function (){
//
},
contentType: "application/x-www-form-urlencoded;charset=UTF-8",
success: function(result){
for(index=result['leftOff']['1']; index <= result['info']['4']-1; index++)
{
if (result[index]['filesize'] < 1000000)
{
result[index]['filesize'] = Math.floor(result[index]['filesize']/1000)+"kb";
$("#ph"+result[index]['id']).append("<div class='filesize'>"+result[index]['filesize']+"</div>");
}
else
{
result[index]['filesize'] = (result[index]['filesize']/1000000).toFixed(2)+"MB";
$("#ph"+result[index]['id']).append("<div class='filesize'>"+result[index]['filesize']+"</div>");
}
if (result[index]['filesize'].length > 0)
{
$("#ph"+result[index]['id']+" .uploading").remove();
$("#ph"+result[index]['id']).append("<img src='layout/cuts/check.png' title='Uploaded' class='done'>");
$("#ph"+result[index]['id']+" .upd").remove();
}
}
$(".eventPop").html("");
$(".eventPop").append('<div class="adding"><p>Uploading files...'+( (result['info'][4]-1)/count * 100).toFixed(0)+'%</p></div>');
if (((result['info'][4]-1)/count * 100).toFixed(0) == 100)
{
setTimeout(function(){
$("progress").remove();
$(".eventPop").html("");
$(".eventPop").append("<div class='adding'>Upload complete!</div>");
setTimeout(function(){
$(".eventPop").html("");
$(".eventPop").append("<div class='adding'><div class='sendPhotos'><form action='#' onsubmit='return false;' method='post' enctype='multipart/form-data'><label>Your email</label><input type='text' class='yemail'/><br/><label>Friend's email</label><input type='text' class='fremail'/><br/><span class='tip'><div class='triangle'></div>You can send photos to multiple friends by typing their e-mail separated by ';'.<br/>Eg. 'thomas#gmail.com ; peter#gmail.com'</span><input type='submit' name='send' class='send' value='Send'></form></div></div>");
},1000);
},1000);
}
if (info[2].length)
{
info[2] = "";
}
if ( (parseInt(result['info']['4'])+parseInt(nrConfig)) >= count )
{
nrConfig = count-result['info']['4']+1;
}
if(result['info']['4'] <= count)
{
for(i=result['info']['4']; i <= parseInt(result['info']['4'])+parseInt(nrConfig); i++)
{
if (i == parseInt(result['info']['4'])+parseInt(nrConfig))
{
info[2] = info[2].substring(2, info[2].length);
uploadImages(nrConfig,result['info']['4']);
}
else
{
info[2] = info[2]+"--"+$("#ph"+i+"").attr("get");
}
}
}
}
});
}
PHP code:
public function receiveImages()
{
$string = strtok($_POST['info'][2],"--");
$currentID = $_POST['info']['4'];
$newArray['info']['3'] = $_POST['info']['3'];
$newArray['leftOff']['1'] = $currentID;
$phAdded = 0;
while($string != false && $phAdded < $_POST['info']['3'])
{
$newArray[$currentID]['id'] = $currentID;
$newArray[$currentID]['filesize'] = $this->saveImages($string,$_POST['info']['1'],$currentID);
$currentID++;
$phAdded++;
$string = strtok("--");
}
$newArray['info']['4'] = $currentID;
echo json_encode($newArray);
}
public function saveImages($base64img = "",$folder = "",$currentID = "")
{
$newArray = array();
if (!is_dir(UPLOAD_DIR.$folder))
{
mkdir(UPLOAD_DIR.$folder,0777);
}
$dir = UPLOAD_DIR.$folder."/";
if (strstr($base64img,'data:image/jpeg;base64,'))
{
$base64img = str_replace('data:image/jpeg;base64,', '', $base64img);
$uniqid = uniqid();
$file = $dir . $uniqid . '.jpg';
$file_name = $uniqid.".jpg";
}
else
{
$base64img = str_replace('data:image/png;base64,', '', $base64img);
$uniqid = uniqid();
$file = $dir . $uniqid . '.png';
$file_name = $uniqid.".png";
}
$data = base64_decode($base64img);
file_put_contents($file, $data);
$size = filesize($file);
if ($size > 1000000)
{
$size = number_format(($size/1000000),2)."MB";
}
else
{
$size = number_format(($size/1000),0)."kb";
}
return filesize($file);
}
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" />