script for upload images not work - php

I need a CMS for make a Manga reader, so I bought PHP Manga: http://codecanyon.net/item/php-manga-manga-reader-website-solution/full_screen_preview/10102963
The problem is that manga images are not uploaded in order. For example, If I select and upload images (or pages) 1, 2, 3... He upload the images in 3,1,2 or so on.
Sadly they doesn't offer support anymore, and when I decided to buy it I didn't knew since I was unable to access to their forum without a license. So I need to fix this problem on my own.
This is the input form:
<?php echo Form::input('uploaderInput', R('uploaderInput'), array("type"=>"file", "data-href"=>URL('admin/base64'), "data-dir"=>"upload/manga/".$thisManga['slug']."/", "id"=>"inputUploader", "class"=>"form-control ", "multiple")) ?>
this is the template
$template->customJs .= '$("#chapterNumber").on("keyup", function(){
$("#chapterInfoDiv").show();
});
function readImage(input) {
for(var i=0,file; file = input.files[i]; i++) {
var FR = new FileReader();
FR.onload = function(e) {
var base64 = e.target.result,
h = $("#inputUploader").data("href"),
d = $("#inputUploader").data("dir")+$("#chapterNumber").val(),
options = {
type: "POST",
url: h,
data: { base64 : base64 , dir : d },
dataType: "json",
success: function(response) {
if(response.s == "ko"){
alert(response.m);
}else if(response.s == "ok"){
$("textarea#inputContent").val($("textarea#inputContent").val()+""+response.m+";");
}
}
};
$.ajax(options);
};
FR.readAsDataURL( input.files[i] );
}
}
$("#inputUploader").change(function(){
readImage( this );
});
';
This is the function
function secure_img_upload($file, $path, $options = array()){
// HANDLE OPTIONS
$validExtensions = isset($options['validExtensions']) ? $options['validExtensions'] : array('jpg', 'jpeg', 'png');
$surfix = isset($options['surfix']) ? $options['surfix'] : '';
// HANDLES FILES
$tempFile = $file['tmp_name'];
$fileName = $file['name'];
$extension = explode(".", $fileName);
$extension = strtolower(end($extension));
$imageName = sha1($fileName.uniqid());
$destination = rtrim($path, '/').'/'.$imageName.$surfix.'.'.$extension;
if(in_array($extension, $validExtensions)) {
$validExtension = true;
} else {
$validExtension = false;
}
// Run getImageSize function to check that we're really getting an image
if(getimagesize($tempFile) == false) {
$validImage = false;
} else {
$validImage = true;
}
if($validExtension == true && $validImage == true) {
if(move_uploaded_file($tempFile, $destination)) {
return $destination;
}else{
return array('s'=>'ko', 'm'=>T("Invalid path."));
}
}else{
return array('s'=>'ko', 'm'=>T("Invalid extension."));
}
Can you please help me to fix this problem? Really, I can't find anything wrong... The uploader is a single input with multi

there are a plugin to fix it
check it on codecanyon
That plugin will fix the order and showing the upload progress(speed,number of byte). The full detail can see on codecanyon

Related

ionic cordovaFileTransfer with api php code error 3

I am developing an application for sharing photos, I used ionic for the mobile part and the php for the backend part. But I have a problem when I upload a file that exceeds 2M.
Thank you very much for your good day.
This is my code:
//PHP backend : upload.php
<?php
header('Access-Control-Allow-Origin: *');
$target_path = "uploads/";
$target_path = $target_path . basename( $_FILES['file']['name']);
if(move_uploaded_file($_FILES['file']['tmp_name'], $target_path)) {
echo "Upload and move success";
} else{
echo $target_path;
echo "There was an error uploading the file, please try again!";
}
header ("Connection: close");
?>
// Ionic js
$scope.selectPicture = function(sourceType) {
var options = {
quality: 100,
destinationType: Camera.DestinationType.FILE_URI,
sourceType: sourceType,
saveToPhotoAlbum: false//,
//targetWidth: 800,
//targetHeight: 800
};
$cordovaCamera.getPicture(options).then(function(imagePath) {
// Grab the file name of the photo in the temporary directory
var currentName = imagePath.replace(/^.*[\\\/]/, '');
//Create a new name for the photo
var d = new Date(),
n = d.getTime(),
newFileName = n + ".jpg";
// If you are trying to load image from the gallery on Android we need special treatment!
if ($cordovaDevice.getPlatform() == 'Android' && sourceType === Camera.PictureSourceType.PHOTOLIBRARY) {
window.FilePath.resolveNativePath(imagePath, function(entry) {
window.resolveLocalFileSystemURL(entry, success, fail);
function fail(e) {
console.error('Error: ', e);
}
function success(fileEntry) {
var namePath = fileEntry.nativeURL.substr(0, fileEntry.nativeURL.lastIndexOf('/') + 1);
// Only copy because of access rights
$cordovaFile.copyFile(namePath, fileEntry.name, cordova.file.dataDirectory, newFileName).then(function(success){
$scope.image = newFileName;
}, function(error){
$scope.showAlert('Error', error.exception);
});
};
}
);
} else {
var namePath = imagePath.substr(0, imagePath.lastIndexOf('/') + 1);
// Move the file to permanent storage
$cordovaFile.moveFile(namePath, currentName, cordova.file.dataDirectory, newFileName).then(function(success){
$scope.image = newFileName;
}, function(error){
$scope.showAlert('Error', error.exception);
});
}
},
function(err){
// Not always an error, maybe cancel was pressed...
})
};
// Returns the local path inside the app for an image
$scope.pathForImage = function(image) {
if (image === null) {
return '';
} else {
return cordova.file.dataDirectory + image;
}
};
$scope.uploadImage = function() {
// Destination URL
var url = "http://myssite.com/upload.php";
// File for Upload
var targetPath = $scope.pathForImage($scope.image);
// File name only
var filename = $scope.image;;
var options = {
fileKey: "file",
fileName: filename,
chunkedMode: false,
mimeType: "multipart/form-data",
params : {'fileName': filename},
headers : { Connection: "close"}
};
$cordovaFileTransfer.upload(url, targetPath, options).then(function(result) {
console.log("SUCCESS: " + JSON.stringify(result.response));
}, function (err) {
console.log("ERROR: " + JSON.stringify(err));
}, function (progress) {
$timeout(function () {
$scope.downloadProgress = (progress.loaded / progress.total) * 100;
console.log("progress: " + progress + " dddd "+JSON.stringify(progress));
console.log("mytime "+$scope.downloadProgress);
$scope.progressval = $scope.downloadProgress;
});
});
My Config : upload max file size : 40M
post max size : 40M
this is my error : ERROR: {"code":3,"source":"file:///data/user/0/com.ionicframework.s‌​ample374926/files/14‌​93805852934.jpg","ta‌​rget":"xxxxxx/… end of stream on Connection{xxxx.:80, proxy=DIRECT# hostAddress=xxxxxx cipherSuite=none protocol=http/1.1} (recycle count=0)"}

Export multiple Highchart as Zip file to my project directory

I have successfully created total 4 different charts in one my page.
I have one button "Download Selected Chart" and on click of this button I need to create one ZIP file with selected chart PDF, Means if I select three charts then create a ZIP with three charts PDF.
Highchair provides functionality to download chart as PDF, SVG, PNG etc but I amn't able to do for multiple selected charts.
I check Highchart export server document -
http://www.highcharts.com/docs/export-module/setting-up-the-server but I don't understand how to use this.
please help me if anyone has an idea, how I can do this?
An example solution to this would be:
Create your charts
var options1 = {
// ...
};
$('#chart1').highcharts(options1);
Ask the Highcharts export server to generate an image of the chart
var exportUrl = 'http://export.highcharts.com/';
var d1 = $.ajax({
url: exportUrl,
// ...
});
Fetch the contents of the generated image
$.when(d1).done(function(v1) {
var p1 = new JSZip.external.Promise(function (resolve, reject) {
JSZipUtils.getBinaryContent(exportUrl + v1[0], function(err, data) {
// ...
});
});
// ...
Use JSZip to construct and save the ZIP file with the contents of the generated images
// ...
Promise.all([p1]).then(function(values) {
var zip = new JSZip();
zip.file("chart1.png", values[0], {binary:true});
zip.generateAsync({type:"blob"})
.then(function(content) {
saveAs(content, "charts.zip");
});
});
});
You can see this (very scrappy) JSFiddle demonstration of how you could get the ZIP file. The steps are as described above, but not connected to any button and instead executed immediately upon entering the site.
Here i post my solution that is work for me.
On Button click, get svg image using High chart export server.
// get selected checkbox
$('.selected_checkbox').each(function( index ){
var obj = {},chart;
chart = $('#each_chart').highcharts();
obj.svg = chart.getSVG();
obj.type = 'image/png';
obj.async = true;
obj.id = chart_id;
// ajax call for svg
$.ajax({
type: "POST",
url: url,// u need to save svg in your folder
data: obj,
success: function(data)
{
// redirect to php function and create zip
window.location = 'php function call';
}
)}
Ajax Function call to create SVG..
ini_set('magic_quotes_gpc', 'off');
$type = $_POST['type'];
$svg = (string) $_POST['svg'];
$filename = 'name';
$id = $_POST['id'];
if (get_magic_quotes_gpc()) {
$svg = stripslashes($svg);
}
// check for malicious attack in SVG
if(strpos($svg,"<!ENTITY") !== false || strpos($svg,"<!DOCTYPE") !== false){
exit("the posted SVG could contain code for a malicious attack");
}
$tempName = $filename.'_'.$id;
// allow no other than predefined types
if ($type == 'image/png') {
$typeString = '-m image/png';
$ext = 'png';
} elseif ($type == 'image/jpeg') {
$typeString = '-m image/jpeg';
$ext = 'jpg';
} elseif ($type == 'application/pdf') {
$typeString = '-m application/pdf';
$ext = 'pdf';
} elseif ($type == 'image/svg+xml') {
$ext = 'svg';
} else { // prevent fallthrough from global variables
$ext = 'txt';
}
$outfile = APPPATH."tempp/$tempName.$ext";
if (!file_put_contents(APPPATH."tempp/$tempName.svg", $svg)) {
die("Couldn't create temporary file.");
}}
Ajax Success function redirect code..
Here you need to read directory files and create PDF from SVG.
After add each PDF to ZIP.
This is Example solution.You have to change code as per your requirement

Check whether the file already exists in jquery

how can I check if uploaded file using jQuery File Uploader filename already exists. I tried below code and it keeps overriding the first file uploaded. What I wanted is to prevent adding the file. Can someone guide me? Thanks.
Code:
$output_dir = "uploads/";
if(isset($_FILES["myfile"])) {
$ret = array();
// This is for custom errors;
// $custom_error= array();
// $custom_error['jquery-upload-file-error']="File already exists";
// echo json_encode($custom_error);
// die();
$error =$_FILES["myfile"]["error"];
//You need to handle both cases
//If Any browser does not support serializing of multiple files using FormData()
if(!is_array($_FILES["myfile"]["name"])) //single file
{
$fileName = $_FILES["myfile"]["name"];
// check if fileName already exists
if (file_exists($fileName)) {
$fileName = $_FILES["myfile"]["name"];
echo "string";
} else {
move_uploaded_file($_FILES["myfile"]["tmp_name"],$output_dir.$fileName);
$ret[]= $fileName;
}
}
else //Multiple files, file[]
{
$fileCount = count($_FILES["myfile"]["name"]);
for($i=0; $i < $fileCount; $i++)
{
$fileName = $_FILES["myfile"]["name"][$i];
move_uploaded_file($_FILES["myfile"]["tmp_name"][$i],$output_dir.$fileName);
$ret[]= $fileName;
}
}
echo json_encode($ret);
}
JS:
$(document).ready(function() {
var baseurl = window.location.protocol + "//" + window.location.host + "/rmc/";
var newurl = baseurl + 'document_items/upload';
var deleteurl = baseurl + 'document_items/delete';
$("#fileuploader").uploadFile({
url : newurl,
fileName : "myfile",
returnType : "json",
multiple : true, //allow multiple file upload
showFileSize : false, // show file size
acceptFiles : "image/*,application/pdf", // files accepted list
formData: {"name":"Ravi","age":31},
showAbort : true, // display abort button on upload
onSuccess:function(files,data,xhr) {
// $("#status").html("<font color='green'>Upload is success</font>");
},
afterUploadAll:function() {
swal({
title : "Success",
text : "File(s) successfuly uploaded.",
type : "success"
});
},
onError: function(files,status,errMsg)
{
swal({
title : "Error",
text : "Aw Snap! Something went wrong.",
type : "error"
});
},
deleteCallback: function (data, pd) {
for (var i = 0; i < data.length; i++) {
$.post(deleteurl, {op: "delete",name: data[i]},
function (resp,textStatus, jqXHR) {
// Show Message
swal("Success!", "File deleted successfuly!", "success");
});
}
pd.statusbar.hide(); // You choice.
}
});
});
Change your code as below and try again.
if(!is_array($_FILES["myfile"]["name"])) //single file
{
$fileName = $_FILES["myfile"]["name"];
// check if fileName already exists
if (file_exists($output_dir.$fileName)) {
$fileName = $_FILES["myfile"]["name"];
echo "string";
} else {
move_uploaded_file($_FILES["myfile"]["tmp_name"],$output_dir.$fileName);
$ret[]= $fileName;
}
}

bootstrap fileinput, show uploaded files and delete them

how can i show and delete previously uploaded files with the great bootstrap-fileinput plugin from krajee, my code is:
html:
<script>
$("#images").fileinput({
uploadAsync: true,
uploadUrl: "upload.php"
}).on("filebatchselected", function(event, files) {
$("#images").fileinput("upload");
});
</script>
upload.php:
<?php
if (empty($_FILES['images'])) {
echo json_encode(['error'=>'No files found for upload.']);
return;
}
$images = $_FILES['images'];
$success = null;
$paths= [];
$filenames = $images['name'];
for($i=0; $i < count($filenames); $i++){
$ext = explode('.', basename($filenames[$i]));
$target = "uploads" . DIRECTORY_SEPARATOR . basename($filenames[$i]);
if(move_uploaded_file($images['tmp_name'][$i], $target)) {
$success = true;
$paths[] = $target;
} else {
$success = false;
break;
}
}
if ($success === true) {
$output = ['uploaded' => $paths];
} elseif ($success === false) {
$output = ['error'=>'Error while uploading images. Contact the system administrator'];
foreach ($paths as $file) {
unlink($file);
}
} else {
$output = ['error'=>'No files were processed.'];
}
echo json_encode($output);
?>
Has anyone an idea ? i think i have to scan the uploads dir and send it back with json or use $output, but i dont know how to this ?
Since you are using json to upload files, you can use it to delete them too. Make another ajax call to the server by sending an array of the image URLs that you want to remove. Then with PHP you can simply unlink them.
So for example: http://jsfiddle.net/fdzsLa0k/1/
var paths = []; // A place to store all the URLs
// Loop through all images
// You can do it for a single image by using an id selector and skipping the looping part
$('.uploaded-img').each(function(i, v) {
paths.push(this.src); // Save found image paths
})
console.log(paths); // Preview the selection in console
// Send the URLs to the server for deletion
$.ajax({
method: 'post',
data: { images: paths },
url: 'ajax.php' // Replace with your ajax-processing file
}).success(function(response) {
console.log(response); // Do fun stuff: notify user, remove images from the loaded HTML
});
uuuhh, the fileinput script need php version higher than 5.3.3, because the plesk panel of my hosting provider supports only 5.3.3 i have the problems, since 11.5 plesk supports multiple php version for each domain on the server, now with php 5.6 everything works great !

uploading file using ajax - echo from PHP tells that file is uploaded, but file is not there

Hello I am trying to get to work this piece of code:
I am trying to build intelligent images uploader, that will care about the html 5 multiple selection bug (or feature as someone can say) which will delete "previous files" when I decide to select few extra. Also it has some primitive approach to permit user selecting file that was selected previously.
This part works fine, I am seeing images previews and also echoing "file" into console corresponds to number of files.
What is strange is return (echo) from PHP script which says that file is in /tmp directory and also size is correct, but file don't get moved.
I checked permissions and set uploaded folder to "lucky" 777.
I checked /tmp folder and file is no there but PHP script is saying taht is here.
I know about that you can't set , it is logical why you can't, but should echo from PHP script shows size and tmp location of this file then if this is a issue ?
code here:
var noveSub = [];
var noveSubMeno = [];
var noveSubVelkost = [];
function samotnyUpload() {
var fd = new FormData();
fd.append('upload', noveSub[0]);
// trying just first file for testing
$.ajax({
url: '/upload/upload.php',
data: fd,
cache: false,
processData: false,
contentType: false,
type: 'POST',
success: function(data){
console.log(data);
}
});
}
function pridatSubory() {
$("li.pridaj").click(function() {
$("input").trigger("click");
});
function pushniNovy(subor) {
noveSub.push(subor);
noveSubMeno.push(subor.name);
noveSubVelkost.push(subor.size);
previewNovy(subor);
}
function previewNovy(subor) {
var li = document.createElement("li");
var img = document.createElement("img");
img.file = subor;
li.appendChild(img);
$(li).insertBefore("li.pridaj");
var reader = new FileReader();
reader.onload = (function(aImg) { return function(e) { aImg.src = e.target.result; }; })(img);
reader.readAsDataURL(subor);
}
var inputElement = document.getElementById("vyberSubor");
inputElement.addEventListener("change", handleFiles, false);
function handleFiles() {
var sub = this.files;
for (i=0; i<sub.length; i++) {
pos = noveSubMeno.indexOf(sub[i].name);
if (pos !== -1) {
if (noveSubVelkost[pos] !== sub[i].size) {
pushniNovy(sub[i]);
}
} else {
pushniNovy(sub[i]);
}
}
}
PHP FILE :
<?php
if ($_FILES["upload"]["error"] > 0)
{
echo "Error: " . $_FILES["upload"]["error"] . "<br>";
}
else
{
echo "Upload: " . $_FILES["upload"]["name"] . "<br>";
echo "Type: " . $_FILES["upload"]["type"] . "<br>";
echo "Size: " . ($_FILES["upload"]["size"] / 1024) . " kB<br>";
echo "Stored in: " . $_FILES["upload"]["tmp_name"];
echo "<br><br>";
echo move_uploaded_file($_FILES["upload"]["tmp_name"], "upload/".$_FILES["file"]["name"]);
}
?>
OUTPUT FROM PHP FILE in console:
Upload: erb128.png<br>Type: image/png<br>Size: 4.734375 kB<br>Stored in: /tmp/phpdTy053<br><br>
It may actually be a syntax problem. You're mixing strings and variables in your move_uploaded_file call. Try this instead:
$destination = "upload/".$_FILES["file"]["name"];
$result = move_uploaded_file($_FILES["upload"]["tmp_name"], $destination);
echo $result;
I rethink this approach. to use PUT for upload. I have read that some benefits are:
small memory footprint even if You are uploading very big files
and also saw scripts that are able to pause upload.
changes to code (only draft):
var xhr = new XMLHttpRequest();
function samotnyUpload() {
xhr.open("put", "http://pingpong.local/upload/upload.php", true);
xhr.setRequestHeader("X-File-Name", noveSubMeno[0]);
xhr.setRequestHeader("X-File-Size", noveSubVelkost[0]);
xhr.send(noveSub[0]);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
console.log(xhr.responseText);
}
};
}
and PHP script:
<?php
$filename = $_SERVER['HTTP_X_FILE_NAME'];
echo $filename;
$filesize = $_SERVER['HTTP_X_FILE_SIZE'];
echo $filesize;
$in = fopen('php://input','r');
$tmp = fopen('tempfile.ext','w');
while($data = fread($in, 1024)) fwrite($tmp, $data);
fclose($in);
fclose($tmp);
?>

Categories