Uploading an image to my website causes a 500 error - javascript
I tried to upload an image in my site and I had made this piece of code that worked very well but now it's going as I planned I tried to modify the url
url: 'ajax/uploadifive.php' in url: './ajax/uploadifive.php' even in url: 'https://www.nanaje.com/ajax/uploadifive.php' but nothing works I don't know why
Here is the Ajax jQuery code
<script type="text/javascript">
$(document).ready(function(){
var _URL = window.URL || window.webkitURL
var bar = $('.bar')
var percent = $('.percent')
var progress_bar_id = '#progress-wrp' //ID of an element for response output
var url = $('#url').val() // Url of the page gallery of image
var ajaxCall
$('#file').change(function () {
var file = $(this)[0].files[0]
img = new Image()
var imgwidth = 0
var imgheight = 0
var minwidth = 640 // Minimum width required W: 640
var minheight = 320 // Minimum length required H: 320
img.src = _URL.createObjectURL(file)
img.onload = function() {
imgwidth = this.width // Original Image Width
imgheight = this.height // Original Length Of The Image
if (imgwidth >= minwidth && imgheight >= minheight) {
var formData = new FormData()
formData.append('fileToUpload', $('#file')[0].files[0])
ajaxCall = $.ajax({
url: 'ajax/uploadifive.php',
type: 'POST',
data: formData,
processData: false,
contentType: false,
dataType: 'json',
beforeSend: function () {
$('.progress-bar').show()
$(progress_bar_id + " .load_file").html('<img src="assets/img/ajax-loader.gif" style="width: 15px; height: 15px;"/>')
$(progress_bar_id + " .cancel").html('Cancel')
},
xhr: function(){
//upload Progress
var xhr = $.ajaxSettings.xhr()
if (xhr.upload) {
xhr.upload.addEventListener('progress', function(event) {
var percent = 0
var position = event.loaded || event.position
var total = event.total
var total_file = Math.round((total / 1024) /1024)
var total_file_kb = Math.round(total / 1024)
if (event.lengthComputable) {
percent = Math.ceil(position / total * 100)
}
//update progressbar
$(progress_bar_id +" .progress-bar").attr("value", percent)
$(progress_bar_id + " .status").text(percent +"%")
$(progress_bar_id + " .status_from").text("from")
if(total_file != 0) {
$(progress_bar_id + " .status_total").text(total_file+'Mb')
} else {
$(progress_bar_id + " .status_total").text(total_file_kb+'Kb')
}
}, true)
}
return xhr
},
success: function (response) {
if(response.status == 1) {
$(progress_bar_id + " .load_file").hide()
$(progress_bar_id + " .cancel").hide()
window.location = url
} else {
$(progress_bar_id + " .load_file").hide()
$(progress_bar_id + " .cancel").text('Failed')
swal({
text: response.returnText,
icon: "info",
})
return false
}
}
})
} else {
swal({
text: "Dezole, imaj sa a twò piti oswa twò gwo kalite, tanpri eseye ankò ak yon lòt imaj ki gen pi bon kalite. Nou sijere ke ou soumèt vèsyon orijinal la, kote ou fe li ak pwòp telefon ou, ki pat janm te redwi oswa chanje.",
icon: "info",
})
return false
}
}
img.onerror = function() {
$("#response").text("fichier a pa bon " + file.type)
}
})
$(document).on('click','.cancel', function() {
ajaxCall.abort()
$(progress_bar_id + " .load_file").hide()
$(progress_bar_id + " .cancel").text('Failed')
})
})
</script>
and here is the php code
<?php
session_start();
require_once '../class/Database.php';
require_once '../includes/functions.php';
require_once '../includes/constants.php';
require_once '../src/interventionImage/autoload.php';
use Intervention\Image\ImageManager;
// We create the instance so that we can use the image
$manager = new ImageManager();
/*
UploadiFive
Copyright (c) 2012 applications réactives, Ronnie Garcia
*/
$returnText = "";
$uploadOk = 1;
// Set the download directory
// We define the user's Id
$id = $_SESSION['user_id'];
$dir_img = '../photos/m/'.$id.'/i';
$uploadDir = "$dir_img/oi"; // Place of destination of the original image
// $uploadDirProfile = "$dir_img/oip"; // Place of destination of the original image
$uploadDirImgHomeProfile = "$dir_img/ihp"; // Place of destination of the img_home_profile
$uploadDirAvatar = "$dir_img/ai"; // Place of destination of the avatar image
$uploadDirImgProfileExtra = "$dir_img/ipe"; // Place of destination of the avatar image
$uploadDirImgGallery = "$dir_img/ig"; // Place of destination of the avatar image
$uploadDirImgMessage = "$dir_img/im"; // Place of destination of the avatar image
$uploadDirStandardProfile = "$dir_img/sp"; // Place of destination of the avatar image
// Let's test the fioxtension
$nomFichier = pathinfo($_FILES['fileToUpload']['name']); //nom complet de l'image avec son extension
$nameFile = $nomFichier['basename']; //nom complet de l'image avec son extension
$extension_file = $nomFichier['extension']; // L'extension de l'image
$field = 'nfo';
$value = $nameFile;
$table = 'pictures';
if(is_already_in_use($field, $value, $table)) {
$returnText = "You have already put this image on the site.";
$uploadOk = 0;
} else {
// Define allowed file extensions
$fileTypes = ['jpg', 'jpeg']; // Allowed file extensions
$verifyToken = md5(uniqid(rand(), true));
$targetPath = $uploadDir; // Place or store the image on the site server
// $targetPathProfile = $uploadDirProfile; // Place or store the image on the site server
$targetPathImgHomeProfile = $uploadDirImgHomeProfile; // Place or store the image on the site server
$targetPathAvatar = $uploadDirAvatar; // Place or store the image on the site server
$targetPathImgProfileExtra = $uploadDirImgProfileExtra; // Place or store the image on the site server
$targetPathImgGallery = $uploadDirImgGallery; // Place or store the image on the site server
$targetPathImgMessage = $uploadDirImgMessage; // Place or store the image on the site server
$targetPathStandardProfile = $uploadDirStandardProfile; // Place or store the image on the site server
$randomFileName = $verifyToken.'.'.$extension_file;
if (!empty($_FILES) && $verifyToken) {
$tempFile = $_FILES['fileToUpload']['tmp_name'];
$targetFile = rtrim($targetPath,'/') . '/' . $randomFileName; // The place where the image will be stored
if(!file_exists($targetPath)) {
mkdir("$dir_img/oi", 0755, true);
}
if (in_array(strtolower($extension_file), $fileTypes)) {
// We take the current image...
$tempFileOriginal = $manager->make($tempFile);
// Img Logo
// $img_logo = $manager->make(WEBSITE_NAME_URL.'/assets/img/Logopit_1571868283797.png')->resize(700, 400); // 700X400 300X300
$tempFileOriginal->orientate()->text('nanaje.com', 720, 1000, function($font) {
$font->file('../assets/img/Texturina-Italic-VariableFont_opsz,wght.ttf');
$font->size(48);
$font->color('#be0210');
})->interlace(true)->save($targetFile, 60);
// $tempFileOriginal->orientate()->insert($img_logo, 'bottom-right', -10, -100)->interlace(true)->save($targetFile, 60);
// save the file, ie the original image
if ($tempFileOriginal) {
$filename = $targetFile;
list($width, $height, $type, $attr) = getimagesize($filename);
if ($width < 640 && $height < 320) {
unlink($filename);
$returnText = "Sorry, this image is too small or of too low a quality, please try again with another image of better quality. We suggest that you submit the original version of your recent photo that has never been reduced or altered.";
$uploadOk = 0;
}
if ($uploadOk == 0) {
$returnText;
} else {
/**
* Create the targetPathProfile for your profile for modal box
*/
// We save the modal box resize image in the file
$thumbnailPathProfile = rtrim($targetPathProfile,'/') . '/' . $randomFileName; // The place where the image will be stored
// We check if this path exists, if not, we create it
if (!file_exists($thumbnailPathProfile)) {
mkdir("$targetPathProfile", 0755, true);
}
$width = 900; // Maximum width
$height = 900; // Maximum height
// We take the current image...
$img = $manager->make($targetFile);
// We check which height or width we should keep...
($img->height() > $img->width()) ? $width = null : $height = null;
$img->orientate()->resize($width, $height, function ($constraint) {
$constraint->aspectRatio();
})->interlace(true)->save($thumbnailPathProfile, 60); //900x900
/** END */
/**
* Create the img_home_profile
*/
// We save the AVATAR resize image in the file
$thumbnailPathImgHomeProfile = rtrim($targetPathImgHomeProfile,'/') . '/' . $randomFileName; // The place where the image will be stored
// We check if this path exists, if not, we create it
if (!file_exists($thumbnailPathImgHomeProfile)) {
mkdir("$targetPathImgHomeProfile", 0755, true);
}
$width = 218; // Maximum width
$height = 218; // Maximum height
// We take the current image...
$img = $manager->make($targetFile);
// Img Logo
// $img_logo = $manager->make(WEBSITE_NAME_URL.'/assets/img/Logopit_1571868283797.png')->resize(700, 400); // 700X400
// $img->orientate()->insert($img_logo, 'bottom-right', -10, -100)->resize($width, $height)->interlace(true)->save($thumbnailPathImgHomeProfile, 60); /90089008
$img->orientate()->resize($width, $height)->interlace(true)->save($thumbnailPathImgHomeProfile, 60); //218x218
/** END */
/**
* Create the Avatar Profile
*/
// We save the AVATAR resize image in the file
$thumbnailPathAvatar = rtrim($targetPathAvatar,'/') . '/' . $randomFileName; // The place where the image will be stored
// We check if this path exists, if not, we create it
if (!file_exists($thumbnailPathAvatar)) {
mkdir("$targetPathAvatar", 0755, true);
}
$width = 500; // Maximum width
$height = 500; // Maximum height
// We take the current image...
$img = $manager->make($targetFile);
// Img Logo
// $img_logo = $manager->make(WEBSITE_NAME_URL.'/assets/img/Logopit_1571868283797.png')->resize(700, 400); // 700X400
// We check which height or width we should keep...
($img->height() > $img->width()) ? $width = null : $height = null;
// $img->orientate()->insert($img_logo, 'bottom-right', -10, -100)->resize($width, $height, function ($constraint) {
$img->orientate()->resize($width, $height, function ($constraint) {
$constraint->aspectRatio();
})->interlace(true)->save($thumbnailPathAvatar, 60); //500x500
/** END */
/**
* Create the Avatar Profile Extra
*/
// We save the AVATAR resize image in the file
$thumbnailPathImgProfileExtra = rtrim($targetPathImgProfileExtra,'/') . '/' . $randomFileName; // The place where the image will be stored
// We check if this path exists, if not, we create it
if (!file_exists($thumbnailPathImgProfileExtra)) {
mkdir("$targetPathImgProfileExtra", 0755, true);
}
$width = 80; // Maximum width
$height = 80; // Maximum height
// We take the current image...
$img = $manager->make($targetFile);
$img->orientate()->fit($width, $height)->interlace(true)->save($thumbnailPathImgProfileExtra, 60); //80x80
/** END */
/**
* Create the Avatar Profile Gallery
*/
// We save the AVATAR resize image in the file
$thumbnailPathImgGallery = rtrim($targetPathImgGallery,'/') . '/' . $randomFileName; // The place where the image will be stored
// We check if this path exists, if not, we create it
if (!file_exists($thumbnailPathImgGallery)) {
mkdir("$targetPathImgGallery", 0755, true);
}
$width = 190; // Maximum width
$height = 190; // Maximum height
// We take the current image...
$img = $manager->make($targetFile);
// Img Logo
// $img_logo = $manager->make(WEBSITE_NAME_URL.'/assets/img/Logopit_1571868283797.png')->resize(700, 400); // 700X400
// $img->orientate()->insert($img_logo, 'bottom-right', -10, -100)->resize($width, $height)->interlace(true)->save($thumbnailPathImgGallery, 60); //80x80
$img->orientate()->resize($width, $height)->interlace(true)->save($thumbnailPathImgGallery, 60); //80x80
/** END */
/**
* Create the Avatar Profile Message
*/
// We save the AVATAR resize image in the file
$thumbnailPathImgMessage = rtrim($targetPathImgMessage,'/') . '/' . $randomFileName; // The place where the image will be stored
// We check if this path exists, if not, we create it
if (!file_exists($thumbnailPathImgMessage)) {
mkdir("$targetPathImgMessage", 0755, true);
}
$width = 32; // Maximum width
$height = 32; // Maximum height
// We take the current image...
$img = $manager->make($targetFile);
// $img->orientate()->fit($width, $height)->interlace(true)->save($thumbnailPathImgMessage, 60); //32x32
$img->orientate()->fit($width, $height)->interlace(true)->save($thumbnailPathImgMessage, 60); //32x32
/** END */
/**
* Create the img_home_profile standard_home
*/
// We save the AVATAR resize image in the file
$thumbnailPathStandardProfile = rtrim($targetPathStandardProfile,'/') . '/' . $randomFileName; // The place where the image will be stored
// We check if this path exists, if not, we create it
if (!file_exists($thumbnailPathStandardProfile)) {
mkdir("$targetPathStandardProfile", 0755, true);
}
$width = 320; // Maximum width
$height = 240; // Maximum height
// We take the current image...
$img = $manager->make($targetFile);
// Img Logo
// $img_logo = $manager->make(WEBSITE_NAME_URL.'/assets/img/Logopit_1571868283797.png')->resize(700, 400); // 700X400
$img->orientate()->fit($width, $height)->interlace(true)->save($thumbnailPathStandardProfile, 60); //32x32
/** END */
unlink($filename);
$q = $db->prepare("INSERT INTO pictures(io, nfo, ihp, ai, ipe, ig, im, sp, rules, picture_added, ip, user_id)
VALUES(:io, :nfo, :ihp, :ai, :ipe, :ig, :im, :sp, :rules, now(), :ip, :user_id)");
$q->execute([
'io' => $thumbnailPathProfile,
'nfo' => $nameFile,
'ihp' => $thumbnailPathImgHomeProfile,
'ai' => $thumbnailPathAvatar,
'ipe' => $thumbnailPathImgProfileExtra,
'ig' => $thumbnailPathImgGallery,
'im' => $thumbnailPathImgMessage,
'sp' => $thumbnailPathStandardProfile,
'rules' => '1',
'ip' => $_SERVER['REMOTE_ADDR'],
'user_id' => $id
]);
$picture_user_id = $db->lastInsertId();
if ($picture_user_id) {
$q = $db->prepare("SELECT id FROM pictures WHERE user_id = ? AND active_profile = ?");
$q->execute([get_session('user_id'), '2']);
$data = $q->fetch(PDO::FETCH_OBJ);
if (!$data) {
$q = $db->prepare("UPDATE pictures SET active_profile = ? WHERE id = ?");
$q->execute(['2', $picture_user_id]);
}
// End of the backup
$q = $db->prepare("SELECT user_id FROM notes_picture_personal WHERE user_id = ?");
$q->execute([$id]);
$data = $q->fetch(PDO::FETCH_OBJ);
// If this is the case we continue ...
if ($data) {
// Then we update the field of the database of the user ...
$q = $db->prepare("UPDATE notes_picture_personal SET notes_picture_perso = notes_picture_perso + 1 WHERE user_id = ?");
$q->execute([$id]);
} else {
// Write the number of fields that have inserted...
$q = $db->prepare("INSERT INTO notes_picture_personal(user_id, notes_picture_perso) VALUES(?, ?)");
$q->execute([$id, 1]);
// End of the backup
}
}
}
} else {
$returnText = "Sorry, there was an error uploading your file.";
$uploadOk = 0;
}
} else {
$returnText = "Sorry, only JPG, JPEG files are allowed.";
$uploadOk = 0;
}
if ($uploadOk == 0) {
$returnText;
}
}
}
echo json_encode(array("status"=>$uploadOk,"returnText"=>$returnText));
?>
and here are the images of the error that is displayed
POST https://www.nanaje.com/ajax/uploadifive.php 500 jquery-3.3.1.min.js:
POST https://www.nanaje.com/ajax/uploadifive.php 500 jquery-3.3.1.min.js:
Related
How to get JS variable value on one page passed back to another page in PHP
I currently have two pages coded in php one page is called upload.php and the other page is called processing.php. in the processing.php I currently have some Javascript that is ran it’s purpose is to check a log file for a video encoding progress to get the percentage left. this variable is called “progress” (This works fine when using console.log on the processing.php and I can see the incrementing percentage) I need to be able to get this value back to my upload.php page so that I can dynamically update a progress bar with its current value. I already have one part of the puzzle working and that's to show a progress bar of the file uploading. I have included some of the JS code on my upload.php and the JS code using in the processing.php page. One thing that I tried was to have the JS variable inserted into a PHP session variable on the processing.php page, then echo this session variable out on the upload.php. I have included in my code snippets below my attempt at using sessions. Upload.php <?php session_start();?> <?php $formProvider = new VideoDetailsFormProvider($con); echo $formProvider->createUploadForm(); ?> </div> <script> $("form").submit(function() { $("#loadingModal").modal("show"); var $el = $("#loadingModal"); $form = $(this); uploadVideo($form, $el); }); function uploadVideo($form, $el){ var formdata = new FormData($form[0]); //formelement var ajax= new XMLHttpRequest(); ajax.upload.addEventListener("progress", function(event){ var percent = Math.round(event.loaded /event.total) * 100; $el.find('#progressBarUpload').width(percent+'%').html(percent+'%'); //console.log(percent); }); //progress completed load event ajax.addEventListener("load", function(event){ $el.find('#progressBarUpload').addClass('progress-bar bg-success').html('Upload completed...'); }); ajax.addEventListener("error", function(event){ $el.find('#status').innerhtml = "Upload Failed"; }); ajax.addEventListener("abort", function(event){ $el.find('#status').innerhtml = "Upload Aborted"; }); ajax.open("POST", "processing.php"); ajax.send(formdata); } Please wait. This might take a while. <?php echo($_SESSION['convertProgress']);?> <div class="progress"> <div id="progressBarUpload" class="progress-bar" role="progressbar" style="width: 0%" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100"></div> </div> Processing.php <?php session_start(); $convertProgressTest = $_SESSION['convertProgress']; ?> <script> var _progress = function(i){ i++; // THIS MUST BE THE PATH OF THE .txt FILE SPECIFIED IN [1] : var logfile = 'uploads/videos/logs/output.txt'; /* (example requires dojo) */ $.post(logfile).then( function(content){ // AJAX success var duration = 0, time = 0, progress = 0; var resArr = []; // get duration of source var matches = (content) ? content.match(/Duration: (.*?), start:/) : []; if( matches.length>0 ){ var rawDuration = matches[1]; // convert rawDuration from 00:00:00.00 to seconds. var ar = rawDuration.split(":").reverse(); duration = parseFloat(ar[0]); if (ar[1]) duration += parseInt(ar[1]) * 60; if (ar[2]) duration += parseInt(ar[2]) * 60 * 60; // get the time matches = content.match(/time=(.*?) bitrate/g); console.log( matches ); if( matches.length>0 ){ var rawTime = matches.pop(); // needed if there is more than one match if ($.isArray(rawTime)){ rawTime = rawTime.pop().replace('time=','').replace(' bitrate',''); } else { rawTime = rawTime.replace('time=','').replace(' bitrate',''); } // convert rawTime from 00:00:00.00 to seconds. ar = rawTime.split(":").reverse(); time = parseFloat(ar[0]); if (ar[1]) time += parseInt(ar[1]) * 60; if (ar[2]) time += parseInt(ar[2]) * 60 * 60; //calculate the progress progress = Math.round((time/duration) * 100); } resArr['status'] = 200; resArr['duration'] = duration; resArr['current'] = time; resArr['progress'] = progress; console.log(resArr); /* UPDATE YOUR PROGRESSBAR HERE with above values ... */ /* $("#progressBarconvert").width(progress+'%').html(progress+'%'); if(progress==100){ $("#progressBarconvert").addClass('progress-bar bg-success').html('Conversion Completed...'); }*/ var convertProgress = progress; if(progress==0 && i>20){ //TODO err - giving up after 8 sec. no progress - handle progress errors here console.log('{"status":-400, "error":"there is no progress while we tried to encode the video" }'); return; } else if(progress<100){ setTimeout(function(){ _progress(i); }, 400); } } else if( content.indexOf('Permission denied') > -1) { // TODO - err - ffmpeg is not executable ... console.log('{"status":-400, "error":"ffmpeg : Permission denied, either for ffmpeg or upload location ..." }'); } }, function(err){ // AJAX error if(i<20){ // retry setTimeout(function(){ _progress(0); }, 400); } else { console.log('{"status":-400, "error":"there is no progress while we tried to encode the video" }'); console.log( err ); } return; }); } setTimeout(function(){ _progress(0); }, 800); </script>
Since you dont want to leave upload.php you have to add return false; right after uploadVideo($form, $el); Otherwise you trigger the upload asynchronously and go to progress.php synchronously(which means you leave upload.php) You have 3 responsibilities here, so you could do it with 3 files: upload.php - display the upload form convert.php - do the conversion progress.php - get the progress In your convert.php you will need to add the line $_SESSION['convertProgress'] = convertProgress; In your upload.php you can update your progressbar now by: $.ajax('progress.php', function(content) { // set element value etc... }); As soon as you start the upload the File gets uploaded and converted by convert.php asynchronously. You can now trigger a JS-Timer, which does the above call to progress.php over and over until it reaches 100. If you want to be able to do some errorhandling you can use JSON to pass more data back to your upload.php which calls progress.php. PHP (example): json_encode([ 'progress' => 0, 'message' => '', ]); JS decode: JSON.parse(<content of progress.php>)
I have managed to resolve this now it's not pretty and it may not be the best way but it works for me, using #Pilan advice and help this is my workaround. have 3 pages The Update.php Page, The Processing.php Page and convertProgress.php, the convertProgress.php Page contains the the Javascript code mentioned at the beginning of my post. The upload.php contains the following. var testing; function beginUpload() { $.ajax({ url: 'convertProgress.php', type: 'POST', //async: false, data: {}, success: function (response) { //we got the response if(response.progress){ testing = response.progress console.log(testing); }else { beginUpload(); getProgress(); } //var testing = response.progress; }, error: function (jqxhr, status, exception) { alert('Exception:', exception); } }); //console.log(testing); } Upload.php also has the same javascript code as the convertProgress.php <script> function getProgress() { var _progress = function (i) { i++; // THIS MUST BE THE PATH OF THE .txt FILE SPECIFIED IN [1] : var logfile = 'uploads/videos/logs/output.txt'; /* (example requires dojo) */ $.post(logfile).then(function (content) { // AJAX success var duration = 0, time = 0, progress = 0; var resArr = []; // get duration of source var matches = (content) ? content.match(/Duration: (.*?), start:/) : []; if (matches.length > 0) { var rawDuration = matches[1]; // convert rawDuration from 00:00:00.00 to seconds. var ar = rawDuration.split(":").reverse(); duration = parseFloat(ar[0]); if (ar[1]) duration += parseInt(ar[1]) * 60; if (ar[2]) duration += parseInt(ar[2]) * 60 * 60; // get the time matches = content.match(/time=(.*?) bitrate/g); console.log(matches); if (matches.length > 0) { var rawTime = matches.pop(); // needed if there is more than one match if ($.isArray(rawTime)) { rawTime = rawTime.pop().replace('time=', '').replace(' bitrate', ''); } else { rawTime = rawTime.replace('time=', '').replace(' bitrate', ''); } // convert rawTime from 00:00:00.00 to seconds. ar = rawTime.split(":").reverse(); time = parseFloat(ar[0]); if (ar[1]) time += parseInt(ar[1]) * 60; if (ar[2]) time += parseInt(ar[2]) * 60 * 60; //calculate the progress progress = Math.round((time / duration) * 100); } resArr['status'] = 200; resArr['duration'] = duration; resArr['current'] = time; resArr['progress'] = progress; console.log(resArr); /* UPDATE YOUR PROGRESSBAR HERE with above values ... */ $("#progressBarconvert").width(progress+'%').html(progress+'%'); if(progress==100){ $("#progressBarconvert").addClass('progress-bar bg-success').html('Conversion Completed...'); } if (progress == 0 && i > 20) { //TODO err - giving up after 8 sec. no progress - handle progress errors here console.log('{"status":-400, "error":"there is no progress while we tried to encode the video" }'); return; } else if (progress < 100) { setTimeout(function () { _progress(i); }, 400); } } else if (content.indexOf('Permission denied') > -1) { // TODO - err - ffmpeg is not executable ... console.log('{"status":-400, "error":"ffmpeg : Permission denied, either for ffmpeg or upload location ..." }'); } }, function (err) { // AJAX error if (i < 20) { // retry setTimeout(function () { _progress(0); }, 400); } else { console.log('{"status":-400, "error":"there is no progress while we tried to encode the video" }'); console.log(err); } return; }); } setTimeout(function () { _progress(0); }, 800); } </script> It's not pretty but it works for me. I hope this helps anyone that would like to get the conversion Progress from FFMPEG and populate a bootstrap Progress bar
How to detect, that drawing a canvas object is finished?
I have following JS code (found here, on stackoverflow, and a little-bit modded), which resize image on client side using canvas. function FileListItem(a) { // Necesary to proper-work of CatchFile function (especially image-resizing). // Code by Jimmy Wärting (https://github.com/jimmywarting) a = [].slice.call(Array.isArray(a) ? a : arguments) for (var c, b = c = a.length, d = !0; b-- && d;) d = a[b] instanceof File if (!d) throw new TypeError('expected argument to FileList is File or array of File objects') for (b = (new ClipboardEvent('')).clipboardData || new DataTransfer; c--;) b.items.add(a[c]) return b.files } function CatchFile(obj) { // Based on ResizeImage function. // Original code by Jimmy Wärting (https://github.com/jimmywarting) var file = obj.files[0]; // Check that file is image (regex) var imageReg = /[\/.](gif|jpg|jpeg|tiff|png|bmp)$/i; if (!file) return var uploadButtonsDiv = document.getElementById('upload_buttons_area'); // Check, that it is first uploaded file, or not // If first, draw a div for showing status var uploadStatusDiv = document.getElementById('upload_status_area'); if (!uploadStatusDiv) { var uploadStatusDiv = document.createElement('div'); uploadStatusDiv.setAttribute('class', 'upload-status-area'); uploadStatusDiv.setAttribute('id', 'upload_status_area'); uploadButtonsDiv.parentNode.insertBefore(uploadStatusDiv, uploadButtonsDiv.nextSibling); // Draw sub-div for each input field var i; for (i = 0; i < 3; i++) { var uploadStatus = document.createElement('div'); uploadStatus.setAttribute('class', 'upload-status'); uploadStatus.setAttribute('id', ('upload_status_id_commentfile_set-' + i + '-file')); uploadStatusDiv.append(uploadStatus); } } var canvasDiv = document.getElementById('canvas-area'); var currField = document.getElementById(obj.id); var currFieldLabel = document.getElementById(('label_' + obj.id)); // Main image-converting procedure if (imageReg.test(file.name)) { file.image().then(img => { const canvas = document.createElement('canvas') canvas.setAttribute('id', ('canvas_' + obj.id)); const ctx = canvas.getContext('2d') const maxWidth = 1600 const maxHeight = 1200 // Calculate new size const ratio = Math.min(maxWidth / img.width, maxHeight / img.height) const width = img.width * ratio + .5|0 const height = img.height * ratio + .5|0 // Resize the canvas to the new dimensions canvas.width = width canvas.height = height // Drawing canvas-object is necessary to proper-work // on mobile browsers. // In this case, canvas is inserted to hidden div (display: none) ctx.drawImage(img, 0, 0, width, height) canvasDiv.appendChild(canvas) // Get the binary (aka blob) canvas.toBlob(blob => { const resizedFile = new File([blob], file.name, file) const fileList = new FileListItem(resizedFile) // Temporary remove event listener since // assigning a new filelist to the input // will trigger a new change event... obj.onchange = null obj.files = fileList obj.onchange = CatchFile }, 'image/jpeg', 0.70) } ) // If file is image, during conversion show status function ShowConvertConfirmation() { if (document.getElementById('canvas_' + obj.id)) { document.getElementById(('upload_status_' + obj.id)).innerHTML = '<font color="#4CAF50">Konwertowanie pliku ' + file.name + ' zakończone!</font>'; return true; } else { document.getElementById(('upload_status_' + obj.id)).innerHTML = '<font color="#4CAF50">Konwertowanie pliku ' + file.name + ' zakończone!</font>'; return false; } } // Loop ShowConvertConfirmation function untill return true (file is converted) var convertConfirmationLoop = setInterval(function() { var isConfirmed = ShowConvertConfirmation(); if (!isConfirmed) { ShowConvertConfirmation(); } else { // Break loop clearInterval(convertConfirmationLoop); } }, 2000); // Check every 2000ms } // If file is not an image, show status with filename else { document.getElementById(('upload_status_' + obj.id)).innerHTML = '<font color="#4CAF50">Dodano plik ' + file.name + '</font>'; //uploadStatusDiv.append(uploadStatus); } } Canvas is drawn in hidden div: <div id="canvas-area" style="overflow: hidden; height: 0;"></div> I am only detect, that div canvas-area is presented and basing on this, JS append another div with status. Unfortunatelly on some mobile devices (mid-range smartphones), message will be showed before finish of drawing (it is wrong). Due to this, some uploaded images are corrupted or stay in original size. How to prevent this?
Everything that should happen after the image has loaded, should be executed within the then callback, or called from within it. It is important to realise that the code that is not within that callback will execute immediately, well before the drawing has completed.
Photoshop javascript batch replace smart layer from folder and resize
I am trying to work out how to use javascript with photoshop, but eventhough i dont find a logical error in the code, it doesnt work properly. I have a folder of 1000+ images/.ai files that have varying dimensions. I need these images on the Pillow and saved as .jpeg. I choose the smartlayer and run the script to choose the images and it saves them correctly. The only problem is, that the resizing of images and positioning dont work properly. If i put the image in manually, it works without issues, but not with the script. If the width is greater than the height, it should set the width to 1200 px and calculate the height according to that. (and vice versa) and place in the middle of the layer. How do i fix the resizing and positioning? Is it possible to choose a folder where the images are inside instead of selecting the images? How do i handle it when there are 2 smart layers to change in the mockup instead of 1? Anyone know where the problem lies this code? Im grateful for any bit of help! // Replace SmartObject’s Content and Save as JPG // 2017, use it at your own risk // Via #Circle B: https://graphicdesign.stackexchange.com/questions/92796/replacing-a-smart-object-in-bulk-with-photoshops-variable-data-or-scripts/93359 // JPG code from here: https://forums.adobe.com/thread/737789 #target photoshop if (app.documents.length > 0) { var myDocument = app.activeDocument; var theName = myDocument.name.match(/(.*)\.[^\.]+$/)[1]; var thePath = myDocument.path; var theLayer = myDocument.activeLayer; // JPG Options; jpgSaveOptions = new JPEGSaveOptions(); jpgSaveOptions.embedColorProfile = true; jpgSaveOptions.formatOptions = FormatOptions.STANDARDBASELINE; jpgSaveOptions.matte = MatteType.NONE; jpgSaveOptions.quality = 8; // Check if layer is SmartObject; if (theLayer.kind != "LayerKind.SMARTOBJECT") { alert("selected layer is not a smart object") } else { // Select Files; if ($.os.search(/windows/i) != -1) { var theFiles = File.openDialog("please select files", "*.psd;*.tif;*.jpg;*.ai", true) } else { var theFiles = File.openDialog("please select files", getFiles, true) }; }; (function (){ var startRulerUnits = app.preferences.rulerUnits; app.preferences.rulerUnits = Units.PIXELS; var bounds = activeDocument.activeLayer.bounds; var height = bounds[3].value - bounds[1].value; var width = bounds[2].value - bounds[0].value; if (height > width){ var newSize1 = (100 / width) * 800; activeDocument.activeLayer.resize(newSize1, newSize1, AnchorPosition.MIDDLECENTER); app.preferences.rulerUnits = startRulerUnits; } else{ var newSize2 = (100 / height) * 800; activeDocument.activeLayer.resize(newSize2, newSize2, AnchorPosition.MIDDLECENTER); app.preferences.rulerUnits = startRulerUnits; } })(); if (theFiles) { for (var m = 0; m < theFiles.length; m++) { // Replace SmartObject theLayer = replaceContents(theFiles[m], theLayer); var theNewName = theFiles[m].name.match(/(.*)\.[^\.]+$/)[1]; // Save JPG myDocument.saveAs((new File(thePath + "/" + theName + "_" + theNewName + ".jpg")), jpgSaveOptions, true,Extension.LOWERCASE); } } }; // Get PSDs, TIFs and JPGs from files function getFiles(theFile) { if (theFile.name.match(/\.(psd|tif|jpg)$/i) != null || theFile.constructor.name == "Folder") { return true } }; // Replace SmartObject Contents function replaceContents(newFile, theSO) { app.activeDocument.activeLayer = theSO; // ======================================================= var idplacedLayerReplaceContents = stringIDToTypeID("placedLayerReplaceContents"); var desc3 = new ActionDescriptor(); var idnull = charIDToTypeID("null"); desc3.putPath(idnull, new File(newFile)); var idPgNm = charIDToTypeID("PgNm"); desc3.putInteger(idPgNm, 1); executeAction(idplacedLayerReplaceContents, desc3, DialogModes.NO); return app.activeDocument.activeLayer }; I have attached 2 pictures. 1 how it needs to look like and 2 what the script outputs Correct Wrong
Your replaced images have to be the same resolution as the smart object. You can declare the folder path in your code. If you still want to select the path by hand, you can select one image in the path, and extract the parent folder path. You can recursively go through all of the layers in the documents and extract all the smart objects that you want to replace. You may want a function to recursively traverse all the layers in the document function browseLayer(layer, fn) { if (layer.length) { for (var i = 0; i < layer.length; ++i) { browseLayer(layer[i], fn) } return; } if (layer.layers) { for (var j = 0; j < layer.layers.length; ++j) { browseLayer(layer.layers[j], fn); } return; } //apply this function for every layer fn(layer) } Get all the smart objects in the document const smartObjects = []; //The smart objects can be visit twice or more //use this object to mark the visiting status const docNameIndex = {}; const doc = app.open(new File("/path/to/psd/file")); browseLayer(doc.layers, function (layer) { //You cannot replace smart object with position is locked if (layer.kind == LayerKind.SMARTOBJECT && layer.positionLocked == false) { smartLayers.push(layer); doc.activeLayer = layer; //open the smart object executeAction(stringIDToTypeID("placedLayerEditContents"), new ActionDescriptor(), DialogModes.NO); //activeDocument is now the smart object const docName = app.activeDocument.name; if (!docNameIndex[docName]) { docNameIndex[docName] = true; smartObjects.push({ id: layer.id, name: layer.name, docName: docName, width : app.activeDocument.width.as('pixels'), height : app.activeDocument.height.as('pixels'), resolution : app.activeDocument.resolution //important }); } //reactive the main document app.activeDocument = doc; } }); I assume that you have two smart objects needed to replace, the images for replacement are stored in different folders with the same name. smartObjects[0].replaceFolderPath = "/path/to/folder/1"; smartObjects[1].replaceFolderPath = "/path/to/folder/2"; //we need temp folder to store the resize images smartObjects[0].tempFolderPath = "/path/to/temp/folder/1"; smartObjects[1].tempFolderPath = "/path/to/temp/folder/2"; Ex: The first iteration will replace smartObjects[0] with "/path/to/folder/1/image1.jpg", and smartObjects[1] with "/path/to/folder/image1.jpg" Now resize all the images following the properties of the smart objects smartObjects.forEach(function(smartObject){ //Get all files in the folder var files = new Folder(smartObject.replaceFolderPath).getFiles(); //Resize all the image files files.forEach(function (file) { var doc = app.open(file); doc.resizeImage( new UnitValue(smartObject.width + ' pixels'), new UnitValue(smartObject.height + ' pixels'), smartObject.resolution ); //save to temp folder doc.saveAs( new File(smartObject.tempFolderPath + "/" + file.name), new PNGSaveOptions(), true ); doc.close(SaveOptions.DONOTSAVECHANGES) }); }); Finally, replace the smart object //get list of file again var files = new Folder(smartObject.replaceFolderPath).getFiles(); files.forEach(function(file){ var fileName = file.name; smartObjects.forEach(function(smartObject){ //active the window opening the smart object app.activeDocument = app.documents.getByName(args.documentName); var desc = new ActionDescriptor(); desc.putPath(charIDToTypeID("null"), new File(smartObject.tempFolderPath + "/" + fileName)); executeAction(stringIDToTypeID( "placedLayerReplaceContents" ), desc, DialogModes.NO); }); //Now export document var webOptions = new ExportOptionsSaveForWeb(); webOptions.format = SaveDocumentType.PNG; // SaveDocumentType.JPEG webOptions.optimized = true; webOptions.quality = 100; doc.exportDocument(new File("/path/to/result/folder" + file.name), ExportType.SAVEFORWEB, webOptions); }); Now you can close all the opening smart objects smartObjects.forEach(function (s) { app.documents.getByName(r.docName).close(SaveOptions.DONOTSAVECHANGES); });
Need Help Merging Template Chatbox with php
I've recently purchased a template from themeforest and it has a perfect chat template that i need to merge with php/ajax? Im trying to make it so rather than just showing on the chatbox until i refresh, it will send to php file and upload to database, same for refreshing chats, so if anyone sends a message it comes up as well. <?php if (isset($_GET['chatMessage'])){ session_start(); require_once("functions.php"); $ChatMessage = htmlspecialchars($_GET['chatMessage']); if (($ChatMessage != "") && (strlen($ChatMessage) < 255)){ $statement = $MySQL->prepare("INSERT INTO `chatbox` VALUES (NULL, ?, ?, ?)"); $statement->bind_param("isi", $_SESSION['memberID'], $ChatMessage, time()); $statement->execute(); } } ?> This above is the sendchat.php This below is the getchat.php that has previously worked on my old website: $statement = $MySQL->query("SELECT * FROM `chatbox` ORDER BY `ID` DESC LIMIT 20"); while ($Chat = $statement->fetch_assoc()){ $MemberID = $Chat['MemberID']; $ChatMessage = $Chat['ChatMessage']; $Time = time_ago($Chat['TimeStamp']); $ChatClass = $MemberID == $_SESSION['memberID'] ? 'chatui-talk-msg' : 'chatui-talk-msg chatui-talk-msg-highlight themed-border'; echo " <li class=\"chatui-talk-msg\"> <img src=\"img/placeholders/avatars/avatar6.jpg\" alt=\"Avatar\" class=\"img-circle chatui-talk-msg-avatar\"> $ChatMessage </li>"; } ?> This was also the javascript used on my old website that worked as well: function startChatBox() { setInterval(function() { refreshShouts(); }, 1500); } function sendShout() { var chatRequest = new XMLHttpRequest(); var shoutMessage = document.getElementById('chatui-message').value; chatRequest.onreadystatechange = function() { if (chatRequest.readyState == 4 && chatRequest.status == 200) {} }, chatRequest.open("GET", "sendChat.php?chatMessage=" + encodeURIComponent(shoutMessage), true); chatRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); chatRequest.send(); document.getElementById('chatui-message').value = ""; refreshShouts(); } function refreshShouts() { $("#chatBox").load("inc/getChat.php"); } I Realise there is alot of code here but i am very confused as to what i could do to achieve my goal here. The code below is the javascript used on the template to print chats to the screen until you refresh: /* * Document : readyChat.js * Author : pixelcave * Description: Custom javascript code used in Chat page */ var ReadyChat = function() { var chatHeight = 600; // Default chat container height in large screens var chatHeightSmall = 300; // Default chat components (talk & people) height in small screens /* Cache some often used variables */ var chatCon = $('.chatui-container'); var chatTalk = $('.chatui-talk'); var chatTalkScroll = $('.chatui-talk-scroll'); var chatPeople = $('.chatui-people'); var chatPeopleScroll = $('.chatui-people-scroll'); var chatInput = $('.chatui-input'); var chatMsg = ''; /* Updates chat UI components height */ var updateChatHeight = function(){ var windowW = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth; if (windowW < 768) { // On small screens chatCon .css('height', (chatHeightSmall * 2) + chatInput.outerHeight()); chatTalk .add(chatTalkScroll) .add(chatTalkScroll.parent()) .add(chatPeople) .add(chatPeopleScroll) .add(chatPeopleScroll.parent()) .css('height', chatHeightSmall); } else if (windowW > 767) { // On large screens chatCon .css('height', chatHeight); chatTalk .add(chatTalkScroll) .add(chatTalkScroll.parent()) .css('height', chatHeight - chatInput.outerHeight()); chatPeople .add(chatPeopleScroll) .add(chatPeopleScroll.parent()) .css('height', chatHeight); } }; return { init: function() { // Initialize default chat height updateChatHeight(); // Update chat UI components height on window resize $(window).resize(function(){ updateChatHeight(); }); // Initialize scrolling on chat talk + people chatTalkScroll .slimScroll({ height: chatTalk.outerHeight(), color: '#000', size: '3px', position: 'right', touchScrollStep: 100 }); chatPeopleScroll .slimScroll({ height: chatPeople.outerHeight(), color: '#fff', size: '3px', position: 'right', touchScrollStep: 100 }); // When the chat message form is submitted chatInput .find('form') .submit(function(e){ // Get text from message input chatMsg = chatInput.find('#chatui-message').val(); // If the user typed a message if (chatMsg) { // Add it to the message list chatTalk .find('ul') .append('<li class="chatui-talk-msg chatui-talk-msg-highlight themed-border animation-expandUp">' + '<img src="img/placeholders/avatars/avatar2.jpg" alt="Avatar" class="img-circle chatui-talk-msg-avatar">' + $('<div />').text(chatMsg).html() + '</li>'); // Scroll the message list to the bottom chatTalkScroll .animate({ scrollTop: chatTalkScroll[0].scrollHeight },150); // Reset the message input chatInput .find('#chatui-message') .val(''); } // Don't submit the message form e.preventDefault(); }); } }; }(); If anyone is able to help me, it would be greatly appreciated. Thank you
upload fails with image greater than 800kb
I have a form where i can drag and drop an image into a canvas and then click an upload button to upload the file to the server. Below is my javascript file and php file. I cannot find where or why this will not allow me to upload something greater than 800kb? I believe its all failing in the php at if(file_put_contents($uploaddir.$randomName, $decodedData)) { but again i dont know why? The sql statment fails to by the way thats why i think its failing at that point in the php file. 32M is php max file size upload. UPDATE... i removed anything to do with uploading with php in the php and only left echo $randomName.":uploaded successfully"; which now leads me to believe there is something wrong in the JS file at $.post('/mods/photogallery/manager/upload.php?gpID=' + bla, dataArray[index], function(data) { for anything greater than 800kb (ish) JS $(document).ready(function() { // Makes sure the dataTransfer information is sent when we // Drop the item in the drop box. jQuery.event.props.push('dataTransfer'); var z = -40; // The number of images to display var maxFiles = 1; var errMessage = 0; // Get all of the data URIs and put them in an array var dataArray = []; // Bind the drop event to the dropzone. $('#drop-files').bind('drop', function(e) { // Stop the default action, which is to redirect the page // To the dropped file var files = e.dataTransfer.files; // Show the upload holder $('#uploaded-holder').show(); $('#drop-files').hide(); // For each file $.each(files, function(index, file) { // Some error messaging if (!files[index].type.match('image.*')) { if(errMessage == 0) { $('#drop-files').html('Hey! Images only'); ++errMessage } else if(errMessage == 1) { $('#drop-files').html('Stop it! Images only!'); ++errMessage } else if(errMessage == 2) { $('#drop-files').html("Can't you read?! Images only!"); ++errMessage } else if(errMessage == 3) { $('#drop-files').html("Fine! Keep dropping non-images."); errMessage = 0; } return false; } // Check length of the total image elements if($('#dropped-files > .image').length < maxFiles) { // Change position of the upload button so it is centered var imageWidths = ((220 + (40 * $('#dropped-files > .image').length)) / 2) - 20; $('#upload-button').css({'left' : imageWidths+'px', 'display' : 'block'}); } // Start a new instance of FileReader var fileReader = new FileReader(); // When the filereader loads initiate a function fileReader.onload = (function(file) { return function(e) { // Push the data URI into an array dataArray.push({name : file.name, value : this.result}); // Move each image 40 more pixels across z = z+40; var image = this.result; // Just some grammatical adjustments if(dataArray.length == 1) { $('#upload-button span').html("1 file to be uploaded"); } else { $('#upload-button span').html(dataArray.length+" files to be uploaded"); } // Place extra files in a list if($('#dropped-files > .image').length < maxFiles) { // Place the image inside the dropzone $('#dropped-files').append('<div class="image" style="background: #fff url('+image+') no-repeat;background-size: cover;background-position: center center;"> </div>'); } else { $('#extra-files .number').html('+'+($('#file-list li').length + 1)); // Show the extra files dialogue $('#extra-files').show(); // Start adding the file name to the file list $('#extra-files #file-list ul').append('<li>'+file.name+'</li>'); } }; })(files[index]); // For data URI purposes fileReader.readAsDataURL(file); }); }); function restartFiles() { // This is to set the loading bar back to its default state $('#loading-bar .loading-color').css({'width' : '0%'}); $('#loading').css({'display' : 'none'}); $('#loading-content').html(' '); // -------------------------------------------------------- // We need to remove all the images and li elements as // appropriate. We'll also make the upload button disappear $('#upload-button').hide(); $('#dropped-files > .image').remove(); $('#extra-files #file-list li').remove(); $('#extra-files').hide(); $('#uploaded-holder').hide(); $('#drop-files').show(); // And finally, empty the array/set z to -40 dataArray.length = 0; z = -40; return false; } $('#upload-button .upload').click(function() { $("#loading").show(); var totalPercent = 100 / dataArray.length; var x = 0; var y = 0; $('#loading-content').html('Uploading '+dataArray[0].name); $.each(dataArray, function(index, file) { bla = $('#gpID').val(); $.post('/mods/photogallery/manager/upload.php?gpID=' + bla, dataArray[index], function(data) { var fileName = dataArray[index].name; ++x; // Change the bar to represent how much has loaded $('#loading-bar .loading-color').css({'width' : totalPercent*(x)+'%'}); if(totalPercent*(x) == 100) { // Show the upload is complete $('#loading-content').html('Uploading Complete!'); // Reset everything when the loading is completed setTimeout(restartFiles, 500); } else if(totalPercent*(x) < 100) { // Show that the files are uploading $('#loading-content').html('Uploading '+fileName); } // Show a message showing the file URL. var dataSplit = data.split(':'); if(dataSplit[1] == 'uploaded successfully') { alert('Upload Was Successfull'); var realData = '<li>'+fileName+' '+dataSplit[1]+'</li>'; $('#drop-files').css({ 'background' :'url(/mods/photogallery/photos/' + dataSplit[0] + ') no-repeat', 'background-size': 'cover', 'background-position' : 'center center' }); $('#uploaded-files').append('<li>'+fileName+' '+dataSplit[1]+'</li>'); // Add things to local storage if(window.localStorage.length == 0) { y = 0; } else { y = window.localStorage.length; } window.localStorage.setItem(y, realData); } else { $('#uploaded-files').append('<li><a href="/mods/photogallery/photos/'+data+'. File Name: '+dataArray[index].name+'</li>'); } }); }); return false; }); // Just some styling for the drop file container. $('#drop-files').bind('dragenter', function() { $(this).css({'box-shadow' : 'inset 0px 0px 20px rgba(0, 0, 0, 0.1)', 'border' : '4px dashed #bb2b2b'}); return false; }); $('#drop-files').bind('drop', function() { $(this).css({'box-shadow' : 'none', 'border' : '4px dashed rgba(0,0,0,0.2)'}); return false; }); // For the file list $('#extra-files .number').toggle(function() { $('#file-list').show(); }, function() { $('#file-list').hide(); }); $('#dropped-files #upload-button .delete').click(restartFiles); // Append the localstorage the the uploaded files section if(window.localStorage.length > 0) { $('#uploaded-files').show(); for (var t = 0; t < window.localStorage.length; t++) { var key = window.localStorage.key(t); var value = window.localStorage[key]; // Append the list items if(value != undefined || value != '') { $('#uploaded-files').append(value); } } } else { $('#uploaded-files').hide(); } }); PHP // We're putting all our files in a directory. $uploaddir = '../photos/'; // The posted data, for reference $file = $_POST['value']; $name = $_POST['name']; $gpID = $_GET['gpID']; // Get the mime $getMime = explode('.', $name); $mime = end($getMime); // Separate out the data $data = explode(',', $file); // Encode it correctly $encodedData = str_replace(' ','+',$data[1]); $decodedData = base64_decode($encodedData); // You can use the name given, or create a random name. // We will create a random name! $randomName = $gpID.'.'.$mime; if(file_put_contents($uploaddir.$randomName, $decodedData)) { $sql = "UPDATE zmods_galleriesphotos SET gpFile = '$randomName' WHERE gpID = '$gpID'"; $rows = $db->query($sql); echo $randomName.":uploaded successfully"; } else { echo "Something went wrong. Check that the file isn't corrupted"; }
Check the upload_max_filesize in your php.ini file (although it should be large enough by default) Check the post_max_size as well If you're uploading multiple files, then also check max_file_uploads The fact that your sql is failing makes me wonder if this is a mysql problem and not a php problem. What is the SQL error that occurs?