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);
}
Related
When I upload multiple images I don't get any info in my console, but when I upload one image then that image's info is shown in my console. What I would like is that if I upload more then one image I can get that info so that I can then loop through it and display it in my page through the addThumbnail() function.
When I upload mutliple images this shows up in my Response in my network tab
{"name":"kitten_01.jpg"}{"name":"kitten_05.jpg"}
and my console in blank, but when I upload one image I get
{"name":"kitten_05.jpg"}
and I get this in my console
Object { name: "kitten_05.jpg" }
Here is my main.js
$(document).ready(function(){
var dropZone = document.getElementById('drop-zone');
$(".upload-area").on('drop', function(e){
e.preventDefault();
var files_list = e.originalEvent.dataTransfer.files;
var formData = new FormData();
for(i = 0; i < files_list.length; i++){
formData.append('file[]', files_list[i]);
}
$.ajax({
url:"upload.php",
method:"POST",
data:formData,
contentType:false,
cache: false,
processData: false,
dataType: 'json',
success:function(response){
addThumbnail(response);
}
})
});
dropZone.ondragover = function(e){
return false;
}
dropZone.ondragleave = function(e){
return false;
}
});
function addThumbnail(data){
var len = $("#drop-zone div.thumbnail").length;
var num = Number(len);
num = num + 1;
var name = data.name;
console.log(data);
$("#uploaded-image").append('<div id="thumbnail_'+num+'" class="thumbnail"></div>');
$("#thumbnail_"+num).append('<img src="uploads/'+name+'" width="100%" height="78%">');
}
and this is my upload.php
$allowed = ['png', 'jpg'];
foreach($_FILES['file']['name'] as $key => $name)
{
$temp = $_FILES['file']['tmp_name'][$key];
$ext = explode('.', $name);
$ext = strtolower(end($ext));
$return_arr = array();
if(in_array($ext, $allowed) && move_uploaded_file($temp, 'uploads/'.$name))
{
$return_arr = array("name" => $name);
}
echo json_encode($return_arr);
}
$allowed = ['png', 'jpg'];
$return_arr = array();
foreach($_FILES['file']['name'] as $key => $name)
{
$temp = $_FILES['file']['tmp_name'][$key];
$ext = explode('.', $name);
$ext = strtolower(end($ext));
if(in_array($ext, $allowed) && move_uploaded_file($temp, 'uploads/'.$name))
{
$return_arr = array("name" => $name);
}
}
echo json_encode($return_arr);
Hi I have been using ajax for many times. But I can't figure out whats the problem with my code this time. My head is blowing up since 2 days. I am using pusher for the realtime notification in CodeIgniter. Here's my code.
$(document).on("click", ".myonoffswitch", function () {
if (confirm("Sure!!! You want to Change the post status?"))
{
var thiss = $(this);
var prod_id = $(this).attr('id');
var status = $(this).attr('value');
var tdid = $(this).parent().prev().attr('class');
var td = $(this).parent().prev();
var adsstatus = $.ajax({type: "POST", dataType: "json", url: base_url + 'init/ads_status', data: {'prod_id': prod_id, 'status': status}});
$.when(adsstatus).done(function (adsstatuss) {
var msg;
msg = adsstatuss;
alert(msg.length);
var updated_status = msg[0].post_status;
alert(updated_status);
//alert(updated_status);
if (updated_status == "0" && tdid == prod_id) {
td.css("background", "#ccffcc");
td.text("On");
thiss.val(updated_status);
}
if (updated_status == "1" && tdid == prod_id) {
td.css("background", "#ffcccc");
td.text("Off");
thiss.val(updated_status);
}
});
}
});
ads_status (method in CodeIgniter)
public function ads_status() {
$prod_id = $_POST['prod_id'];
$status = $_POST['status'];
if ($status == "1") {
$new_status = "0";
$this->cmsdbmodel->ads_status($prod_id, $new_status);
$dat = $this->cmsdbmodel->get_updated_status($prod_id);
$ads_type = "product";
$emailreturn = $this->send_email_ads_status($prod_id, $ads_type);
//send user alert of product//
if ($dat[0]->post_status == "0") {
$lastInsertedId = $prod_id;
$modelNBrandId = $this->dbmodel->checkProductContainsAlert($lastInsertedId);
$getAlertEmail = $this->dbmodel->getAlertEmailFromBrandNModelId($modelNBrandId);
if (!empty($getAlertEmail)) {
foreach ($getAlertEmail as $alerts) {
$alertsEmail = $alerts->email;
}
}
$alertsPost = $this->dbmodel->getPostAlerts($lastInsertedId);
$sendPostAlerts = json_encode($alertsPost);
$encrytpEmail = hash('sha256', $alertsEmail);
$this->pusher->trigger($encrytpEmail, 'alerts', $sendPostAlerts);
}
//send user alert of product//
$realtime = $this->realTime_charts();
$realtime["post_status"] = $dat[0]->post_status;
$realtime["emailres"] = $emailreturn;
$data = $realtime;
$this->pusher->trigger('recent_activity', 'new_event1', $data);
echo json_encode($data);
}
}
Here I want to trigger event in pusher as well as echo json object. But in ajax, response is undefined. Also in console I can see json but when alerting the reponse it says undefined. Wheres problem in my code. Please help me.
First of all I'm very new to PHP and a bit better with Jquery. I managed to build an upload iFrame to upload images to a dropbox account for a webshop.
So somebody puts a T-shirt in the cart and then needs to upload some artwork. Customer clicks "upload" and is send to an iFrame which have the dropbox upload script. The url of the iFrame is something like this -> http://webshop.com/dropbox/index.html?id=10102013-88981
So far so good. The problem is however that when two people upload a file with the same name, the first file is being updated. So I need to have an unique id in front of the file. That unique id is the parameter at the end of the url.
So the question is how to get the id at the end of the url and how to place it in front of the uploaded image?
Ideal would be either a prefix for the file name or store everything in it's own folder.
I tried several things but my knowledge is limited, so any help greatly appreciated.
The upload script:
//Start the upload code.
........
......
if(sizeof($_FILES)===0){
echo "<li>No files were uploaded.</li>";
return;
}
foreach ($_FILES['ufiles']['name'] as $key => $value) {
if ($_FILES['ufiles']['error'][$key] !== UPLOAD_ERR_OK) {
echo $_FILES['ufiles']['name'][$key].' DID NOT upload.';
return;
}
$tmpDir = uniqid('/tmp/DropboxUploader-');
if (!mkdir($tmpDir)) {
echo 'Cannot create temporary directory!';
return;
}
$tmpFile = $tmpDir.'/'.str_replace("/\0", '_', $_FILES['ufiles']['name'][$key]);
if (!move_uploaded_file($_FILES['ufiles']['tmp_name'][$key], $tmpFile)) {
echo $_FILES['ufiles']['name'][$key].' - Cannot rename uploaded file!';
return;
}
try {
$uploader = new DropboxUploader($drop_account, $drop_pwd );
$uploader->upload($tmpFile, $drop_dir);
echo "<li>".$_FILES['ufiles']['name'][$key]."</li>" ;
// Clean up
if (isset($tmpFile) && file_exists($tmpFile))
unlink($tmpFile);
if (isset($tmpDir) && file_exists($tmpDir))
rmdir($tmpDir);
} catch(Exception $e) {
$error_msg = htmlspecialchars($e->getMessage());
if($error_msg === 'Login unsuccessful.' ) {
echo '<li style="font-weight:bold;color:#ff0000;">Unable to log into Dropbox</li>';
return;
}
if($error_msg === 'DropboxUploader requires the cURL extension.' ) {
echo '<li style="font-weight:bold;color:#ff0000;">Application error - contact admin.</li>';
return;
}
echo '<li>'.htmlspecialchars($e->getMessage()).'</li>';
}
}
UPDATE AS REQUESTED
The form:
<form class="formclass" id="ufileform" method="post" enctype="multipart/form-data">
<fieldset>
<div><span class="fileinput"><input type="file" name="ufiles" id="ufiles" size="32" multiple /></span>
</div>
</fieldset>
<button type="button" id="ubutton">Upload</button>
<button type="button" id="clear5" onclick="ClearUpload();">Delete</button>
<input type="hidden" name="id" id="prefix" value="" />
</form>
Upload.js (file is downloadable as free script on the internet):
(function () {
if (window.FormData) {
var thefiles = document.getElementById('ufiles'), upload = document.getElementById('ubutton');//, password = document.getElementById('pbutton');
formdata = new FormData();
thefiles.addEventListener("change", function (evt) {
var files = evt.target.files; // FileList object
var i = 0, len = this.files.length, file;
for ( ; i < len; i++ ) {
file = this.files[i];
if (isValidExt(file.name)) { //if the extension is NOT on the NOT Allowed list, add it and show it.
formdata.append('ufiles[]', file);
output.push('<li>', file.name, ' <span class="exsmall">',
bytesToSize(file.size, 2),
'</span></li>');
document.getElementById('listfiles').innerHTML = '<ul>' + output.join('') + '</ul>';
}
}
document.getElementById('filemsg').innerHTML = '';
document.getElementById('filemsgwrap').style.display = 'none';
document.getElementById('ubutton').style.display = 'inline-block';
document.getElementById('clear5').style.display = 'inline-block';
}, false);
upload.addEventListener('click', function (evt) { //monitors the "upload" button and posts the files when it is clicked
document.getElementById('progress').style.display = 'block'; //shows progress bar
document.getElementById('ufileform').style.display = 'none'; //hide file input form
document.getElementById('filemsg').innerHTML = ''; //resets the file message area
$.ajax({
url: 'upload.php',
type: 'POST',
data: formdata,
processData: false,
contentType: false,
success: function (results) {
document.getElementById('ufileform').style.display = 'block';
document.getElementById('progress').style.display = 'none';
document.getElementById('filemsgwrap').style.display = 'block';
document.getElementById('filemsg').innerHTML = '<ul>' + results + '</ul>';
document.getElementById('listfiles').innerHTML = '<ul><li>Select Files for Upload</ul>';
document.getElementById('ufiles').value = '';
document.getElementById('ubutton').style.display = 'none';
document.getElementById('clear5').style.display = 'none';
formdata = new FormData();
output.length = 0;
}
});
}, false);
} else {
// document.getElementById('passarea').style.display = 'none';
document.getElementById('NoMultiUploads').style.display = 'block';
document.getElementById('NoMultiUploads').innerHTML = '<div>Your browser does not support this application. Try the lastest version of one of these fine browsers</div><ul><li><img src="images/firefox-logo.png" alt="Mozilla Firefox" /></li><li><img src="images/google-chrome-logo.png" alt="Google Chrome Firefox" /></li><li><img src="images/apple-safari-logo.png" alt="Apple Safari" /></li><li><img src="images/maxthon-logo.png" alt="Maxthon" /></li></ul>';
}
document.getElementById('multiload').style.display = 'block';
document.getElementById('ufileform').style.display = 'block';
}());
function ClearUpload() { //clears the list of files in the 'Files to Upload' area and resets everything to be ready for new upload
formdata = new FormData();
output.length = 0;
document.getElementById('ufiles').value = '';
document.getElementById('listfiles').innerHTML = 'Select Files for Upload';
document.getElementById('ubutton').style.display = 'none';
document.getElementById('clear5').style.display = 'none';
document.getElementById('filemsgwrap').style.display = 'none';
}
function getExtension(filename) { //Gets the extension of a file name.
var parts = filename.split('.');
return parts[parts.length - 1];
}
function isValidExt(filename) { //Compare the extension to the list of extensions that are NOT allowed.
var ext = getExtension(filename);
for(var i=0; i<the_ext.length; i++) {
if(the_ext[i] == ext) {
return false;
break;
}
}
return true;
}
Change this line
$tmpFile = $tmpDir.'/'. $_POST['id'] . '-' . str_replace("/\0", '_', $_FILES['ufiles']['name'][$key]);
Note the $_POST['id'] which was added
EDIT: Changed to $_POST
Also in your form which you are posting add
<input type="hidden" name="id" value="<?=$_GET['id']; ?>" />
You could simply at time() to your file name.
http://php.net/manual/de/function.time.php
$tmpDir. '/' . time() . str_replace("/\0", '_', $_FILES['ufiles']['name'][$key]);
How to run 2 PHP script simultaniously (synchronous) for monitoring a popen command?
I have a script launching a command like this:
7za a -t7z -mx9 backup.7z "H:\Informatique\*"
And I would like to display the progress of the compression on a page using jQuery and PHP.
The php script running this command look like this:
if( ($fp = popen("7za a -t7z ".$GLOBALS["backup_compression"]." \"".$backuplocation.$backupname."\" \"".$pathtobackup."\"", "r")) ) {
while( !feof($fp) ){
$fread = fread($fp, 256);
$line_array = preg_split('/\n/',$fread);
$num_lines = count($line_array);
$_SESSION['job'][$jobid]['currentfile'] = $_SESSION['job'][$jobid]['currentfile']+$num_lines;
$num_lines = 0;
flush();
}
pclose($fp);
}
jQuery call the 7za script then jquery call the listener (listener.php) each 1000ms. the listener.php page contain the following code:
session_start();
$jobid = $_GET['jobid'];
if(!isset($_SESSION['job'][$jobid])) { $arr = array("error"=>"Job not found"); echo json_encode($arr); exit(); };
$arr = array(
"curfile" => $_SESSION['job'][$jobid]['currentfile'],
"totalfiles" => $_SESSION['job'][$jobid]['totalfiles'],
);
echo json_encode($arr);
$jobid = null;
$arr = null;
exit();
After the jquery call is complete (with the listener and we got a response from the server) we display the information with something normal like: $("currentfile").text(data['curfile']);
The problem is that the listener is in an infinite loop waiting for the first script to complete... and that's not the job of the listener... It's listening at the end of everything... when you listen, it's to know what's happening. :P
Do you have any idea what's going on and how can I fix this problem?
Or maybe you can help me with a new approch to this problem?
As always, any suggestions will be welcome.
Thank you.
EDIT
jQuery script:
function backup_launch(jobid) {
x('jobid: '+jobid+' on state '+state);
x('Listener launched');
listen(jobid);
timeout = setTimeout("listen('"+jobid+"')", 500);
$.ajax({
url:'backup.manager.php?json&jobid='+jobid+'&state='+state,
dataType:'json',
success:function(data)
{
state = 3;
}
});
}
function listen(jobid) {
$.ajax({
url:'backup.listener.php?json&jobid='+jobid,
dataType:'json',
success:function(data)
{
var curfile = data['curfile'];
var totalfiles = data['totalfiles'];
var p = curfile * 100 / totalfiles;
x('File '+curfile+' out of '+totalfiles+' progress%: '+p);
timeout = setTimeout("listen('"+jobid+"')", 500);
}
});
}
EDIT 2
I found Gearman (http://gearman.org/) but I don't know at all how to implement this and it needs to be portable/standalone... I'll try to investigate that.
EDIT 3
Full code for the backup.manager.php page. The script is sending the response right aay, but do the job in the background.
The listen.php page still wait for the command to finish before returning any results.
$jobid = isset($_GET['jobid']) ? $_GET['jobid'] : 0;
//Make sure jobid is specified
if($jobid == 0) { return; }
header("Connection: close");
#ob_end_clean();
ignore_user_abort();
ob_start();
echo 'Launched in backgroud';
$size = ob_get_length();
header("Content-Length: ".$size);
ob_end_flush();
flush();
$_SESSION['job'][$jobid]['currentfile'] = 0;
// 3. When app appove backup,
// - Write infos to DB
// - Zip all files into 1 backup file
$datebackup = time();
$bckpstatus = 1; //In progress
$pathtobackup = $_SESSION['job'][$jobid]['path'];
/*
$query = "INSERT INTO backups (watchID, path, datebackup, checksum, sizeori, sizebackup, bckpcomplete)
VALUES ($watchID, '{$path}', '{$datebackup}', '', '{$files_totalsize}', '', '{$bckpstatus}')";
$sth = $db->prepare($query);
$db->beginTransaction();
$sth->execute();
$db->commit();
$sth->closeCursor();
*/
$backupname = $jobid.".".$GLOBALS["backup_ext"];
$backuplocation = "D:\\";
if( ($fp = popen("7za a -t7z ".$GLOBALS["backup_compression"]." \"".$backuplocation.$backupname."\" \"".$pathtobackup."\"", "r")) ) {
while( !feof($fp) ){
$fread = fread($fp, 256);
$line_array = preg_split('/\n/',$fread);
$num_lines = count($line_array);
$_SESSION['job'][$jobid]['currentfile'] = $_SESSION['job'][$jobid]['currentfile']+$num_lines;
$num_lines = 0;
sleep(1);
flush();
}
pclose($fp);
}
Jeremy,
A couple of months ago, I answered a similar question about running server-side batch jobs in a *NIX/PHP environment. If I understand correctly, your requirement is different but it's possible there might be something in the answer which will help.
Run a batch file from my website
EDIT
Here's a modified version of your client-side code. You will see that the main things I have changed are :
to move listen(jobid); inside backup_launch's success handler.
to add error handlers so you can observe errors.
Everything else is just a matter of programming style.
function backup_launch(jobid) {
x(['jobid: ' + jobid, 'on state', state].join(' '));
$.ajax({
url: 'backup.manager.php',
data: {
'json': 1,
'jobid': jobid,
'state': state
}
dataType: 'json',
success:function(data) {
state = 3;
x("Job started: " + jobid);
listen(jobid);
x("Listener launched: " + jobid);
},
error: function(jqXHR, textStatus, errorThrown) {
x(["backup.manager error", textStatus, errorThrown, jobid].join(": "));
}
});
}
function listen(jobid) {
$.ajax({
url: 'backup.listener.php',
data: {
'json': 1
'jobid': jobid
},
dataType: 'json',
success: function(data) {
var curfile = data.curfile;
var totalfiles = data.totalfiles;
var p = curfile * 100 / totalfiles;
x(['File', curfile, 'out of', totalfiles, 'progress%:', p].join(' '));
timeout = setTimeout(function() {
listen(jobid);
}, 500);
},
error: function(jqXHR, textStatus, errorThrown) {
x(["Listener error", textStatus, errorThrown, jobid].join(": "));
}
});
}
I've decided to call the command for each individual file.
It is going to be slower, but it is safer to manage with file cause errors and which files was properly inserted in the archive.
I'll try to find something faster is the direcotry to archive got 10 000 icons file for exemple. Maybe 5 files at a time instead of one file at a time.
This code was intended for testing purposes, the code is not optimized at all for production.
index.html jquery script:
var state = 0;
var jobid = '';
var timeout;
var jobfiles;
var jobpaths = [];
$(document).ready(function() {
$("button").click(function(e) {
e.preventDefault();
console.log('Sending');
var path = $("input").val();
x('state 1 getting info - infpb');
state = 1;
$.ajax({
url:'backup.manager.php?json&path='+encodeURI(path)+'&type=0&state='+state,
dataType:'json',
success:function(data)
{
jobid = data['stats']['jobid'];
jobfiles = data['stats']['totalfiles'];
var jobsize = data['stats']['totalsize'];
for(var i = 0, len = jobfiles; i < len; i++) {
jobpaths.push(data[i]['File']);
}
state = 2;
x('state 2 - infpb stop (Information retrieved, launch backup) '+jobfiles+' files with '+jobsize+' bytes');
backup_launch(jobid);
}
});
});
});
function x(x) {
$("#l").append(x+"<br>");
}
var curfileid = 0;
function backup_launch(jobid) {
x('jobid: '+jobid+' on state '+state);
$.ajax({
url:'backup.manager.php',
data: {
'json': 1,
'jobid': jobid,
'state': state,
'path': jobpaths[curfileid]
},
dataType:'json',
success:function(data)
{
if(curfileid < jobfiles) {
x((curfileid+1)+' / '+jobfiles);
curfileid++;
backup_launch(jobid);
}
},
error: function(jqXHR, textStatus, errorThrown) {
x(["backup.manager error", textStatus, errorThrown, jobid].join(": "));
}
});
}
function listen(jobid) {
$.ajax({
url:'backup.listener.php?json&jobid='+jobid,
dataType:'json',
success:function(data)
{
var curfile = data['curfile'];
var totalfiles = data['totalfiles'];
var p = curfile * 100 / totalfiles;
x('File '+curfile+' out of '+totalfiles+' progress%: '+p);
timeout = setTimeout("listen('"+jobid+"')", 500);
}
});
}
backup.manager.php
set_time_limit(0);
require('../functions.php');
session_start();
$keepCPUlow_lastlookup = time();
$keepCPUlow_mindelay = 60;
function keepCPUlow() {
global $keepCPUlow_lastlookup, $keepCPUlow_mindelay;
if((time() - $keepCPUlow_lastlookup) > $keepCPUlow_mindelay) {
$keepCPUlow_lastlookup = time();
getSysload(75, 1000); // Max %, wait time in ms
}
}
$state = isset($_GET['state']) ? $_GET['state'] : 0;
if($state == '1') {
//
$json = isset($_GET['json']) ? true : false;// Result should be in json format
$path = isset($_GET['path']) ? $_GET['path'] : ''; // Path of the file or folder to backup
$type = isset($_GET['type']) ? $_GET['type'] : ''; // Type - not very useful, for now
//0. Assign a jobid for this job, it will help retrieve realtime information about this task
$jobid = hash('md4', (time().uniqid().session_id()));
//Store the current status (0) job not started
$_SESSION['job'][$jobid]['status'] = 0; //Not started... yet
// 1. Retrive list of files and stats
$fileslist = array(); //Will contain the list of files
$files_totalsize = 0; // Total size of files
// Check if file or folder
if(is_dir($path)) {
//Path is a folder, get the list of files
$files = getFilelist($path);
foreach($files as $file) { //For each files
if(!is_dir($file['File'])) { //That is not a directory
$files_totalsize = $files_totalsize+$file['Filesize']; //Increment toal size
$cpumon = keepCPUlow(); //if($cpumon[1]) echo ">CPU BURN".$cpumon[0]."<";
}
}
$files_total = count($files); // Number of files
} else {
$files_totalsize = $files_totalsize+getFilesize($path);
$files_total = 1;
}
$files['stats'] = array("totalfiles"=>$files_total, "jobid"=>$jobid, "totalsize"=>$files_totalsize);
//Store infos in session
$_SESSION['job'][$jobid]['totalfiles'] = $files_total;
$_SESSION['job'][$jobid]['totalsize'] = $files_totalsize;
$_SESSION['job'][$jobid]['path'] = is_dir($path) ? $path.'\\*' : $path;
$_SESSION['job'][$jobid]['currentfile'] = 0;
$_SESSION['job'][$jobid]['currentfile_path'] = '';
$_SESSION['job'][$jobid]['bname'] = "SafeGuard_".$jobid.".".$GLOBALS["backup_ext"];
$_SESSION['job'][$jobid]['blocation'] = "D:\\";
// 2. return to app and wait for ready confirmation
if(isset($_GET['json'])) {
echo json_encode($files);
}
exit();
}
else if($state == '2') {
$jobid = isset($_GET['jobid']) ? $_GET['jobid'] : 0;
$_SESSION['job'][$jobid]['currentfile'] = 0;
// 3. When app appove backup,
// - Write infos to DB
// - Zip all files into 1 backup file
$datebackup = time();
$bckpstatus = 1; //In progress
//$pathtobackup = $_SESSION['job'][$jobid]['path'];
$pathtobackup = isset($_GET['path']) ? $_GET['path'] : "--";
$backupname = $_SESSION['job'][$jobid]['bname'];
$backuplocation = $_SESSION['job'][$jobid]['blocation'];
/*
$query = "INSERT INTO backups (watchID, path, datebackup, checksum, sizeori, sizebackup, bckpcomplete)
VALUES ($watchID, '{$path}', '{$datebackup}', '', '{$files_totalsize}', '', '{$bckpstatus}')";
$sth = $db->prepare($query);
$db->beginTransaction();
$sth->execute();
$db->commit();
$sth->closeCursor();
*/
if( ($fp = popen("7za a -t7z ".$GLOBALS["backup_compression"]." \"".$backuplocation.$backupname."\" \"".$pathtobackup."\"", "r")) ) {
while( !feof($fp) ){
fread($fp, 256);
$num_lines = 1;
$_SESSION['job'][$jobid]['currentfile'] = $_SESSION['job'][$jobid]['currentfile']+$num_lines;
$num_lines = 0;
flush();
echo '1';
}
pclose($fp);
}
}
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" />