Fixing a 500 Internal Server Error on large image process - php

Information: I have already looked around for answers on SO, Google and other places with no avail. Please do not redirect me to other answers or websites unless it involves new information.
I am building a huge website which converts thousands of images in one go and uploads details of these images to the Database (All images are already uploaded via FTP). The process only creates thumbnails and creates image links in the tables.
The problem: The process takes on average 30 minutes to complete. After roughly 15 minutes, the site displays a 500 Internal Server Error and the website will not reload until the process has completed. The process will still complete as it should in the background? (No idea how this works, but it does). No errors are recorded on the server as I have checked.
Attempted Solutions: I have already attempted a couple things...
Adding this to the .htaccess file
<IfModule mod_php5.c>
php_value max_execution_time 0
php_value max_input_time 0
php_value memory_limit 5000M
php_value post_max_size 5000M
php_value upload_max_filesize 5000M
</IfModule>
Using set_time_limit(0); within the function and the script itself.
I have looked at the option to update the httpd.conf file to change the MaxRequestLen but I'm not sure if that would be the correct thing to do in this circumstance?
Scripts:
Batch Upload Script -
if(isset($_GET['create_all_albums'])){
$length2 = 8;
$randomString2 = substr(str_shuffle("0123456789"), 0, $length2);
setcookie('album_error_log', $randomString2, time() + (3600), "/");
$starting_folder = $_GET['create_all_albums'];
$date_time = date("Y-m-d H:i:s");
$useridnu = $_SESSION['userid'];
$useremail = $_SESSION['email_address'];
mysqli_query($conn,"INSERT INTO new_recent_batch_uses (use_id,user_id,email_address,error_ref,batched_folder,batch_started,batch_completed) VALUES ('','$useridnu','$useremail','$randomString2','$starting_folder','$date_time','$date_time')");
$i = 0;
$c = 0;
$paths = scandir($starting_folder);
foreach($paths as $path){
if($path == '.' || $path == '..'){
} else {
$path = $starting_folder.$path;
$folders = scandir($path);
$count_requests = count($folders);
$arr_content2 = array();
$com = 0;
foreach($folders as $folder){
if($folder == '.' || $folder == '..'){
} else {
++$i;
$file_name = $path.'/'.$folder;
if (substr($file_name, -1, 1) == '/')
{
$file_name = substr($file_name, 0, -1);
}
$string_1 = $file_name;
$string_1 = substr($string_1, 0, strrpos( $string_1, '/'));
$club_name = substr(strrchr($file_name, "/"), 1);
if($club_name == 'xots'){
$club_name = 'ots';
} else {
$club_name = $club_name;
}
$club_date = substr(strrchr($string_1, "/"), 1);
$club_date = chunk_split($club_date, 2, '/');
$club_date = rtrim($club_date, "/");
$club_date = substr_replace($club_date, '20', 6, 0);
$club_date = str_replace('/', '-', $club_date);
$club_date = date('Y-m-d', strtotime($club_date));
$cutyear = substr($string_1, 0, strrpos( $string_1, '/'));
$year = substr(strrchr($cutyear, "/"), 1);
$club_area = substr($cutyear, 0, strrpos( $cutyear, '/'));
$club_area = substr(strrchr($club_area, "/"), 1);
$getvenueinfo = mysqli_fetch_assoc(mysqli_query($conn, "SELECT * FROM `new_categories` WHERE `short_code` = '$club_name' AND `cat_city` = '$club_area' AND `allow_albums` = '1'"));
$cat_id_2 = $getvenueinfo['cat_id'];
$cat_name_2 = $getvenueinfo['cat_name'];
$cat_down_lvl_2 = $getvenueinfo['cat_down_lvl'];
$album_name = date("D dS M Y", strtotime($club_date));
$album_date = date("Y-m-d", strtotime($club_date));
$todays_date = date("Y-m-d");
if(!$cat_id_2 == '' || !$cat_name_2 == '' || !$cat_down_lvl_2 == ''){
$length = 25;
$randomString = substr(str_shuffle("0123456789"), 0, $length);
if($album_date == '1970-01-01'){
$date_time = date("Y-m-d H:i:s");
mysqli_query($conn,"INSERT INTO new_upload_error_log (error_id,error_ref,error_type,error_image,error_album,error_date,success) VALUES ('','$randomString2','Album Creation was unsuccessful (Album date does not seem correct)...','$file_name','','$date_time','4')");
} else {
$search_ID = true;
while($search_ID == true) {
$sqla = "SELECT * FROM `new_albums` WHERE `album_ref` = '$randomString'";
$resulta = $conn->query($sqla);
if (!$resulta->num_rows > 0) {
$sqlc = "SELECT * FROM `new_albums` WHERE `album_name` = '$album_name' AND `venue_name` = '$cat_name_2' AND `city_name` = '$club_area'";
$resultc = $conn->query($sqlc);
if (!$resultc->num_rows > 0) {
mysqli_query($conn,"INSERT INTO new_albums (album_id,album_name,album_desc,album_password,album_date,venue_name,venue_short_code,city_name,cat_id,album_ref,date_added,amount_of_files,viewed_count)
VALUES ('','$album_name','','','$album_date','$cat_name_2','$club_name','$club_area','$cat_down_lvl_2','$randomString','$todays_date','0','0')");
mysqli_query($conn, "UPDATE new_categories SET `last_updated` = '$todays_date' WHERE `cat_down_lvl` = '$cat_id'");
++$c;
if($image_convert_on_album_create == 1){
$com++;
$percent = intval($com/$count_requests * 100);
$arr_content2['percent'] = $percent;
$arr_content2['message'] = $com . " folders(s) processed.";
create_thumbs($conn, $randomString, $file_name, $randomString2);
file_put_contents("tmp2/" . session_id() . ".txt", json_encode($arr_content2));
} else {
}
} else {
$date_time = date("Y-m-d H:i:s");
mysqli_query($conn,"INSERT INTO new_upload_error_log (error_id,error_ref,error_type,error_image,error_album,error_date,success) VALUES ('','$randomString2','Album Creation was unsuccessful (Album already exists)...','$file_name','','$date_time','4')");
}
$search_ID = false;
}
}
}
} else {
$date_time = date("Y-m-d H:i:s");
mysqli_query($conn,"INSERT INTO new_upload_error_log (error_id,error_ref,error_type,error_image,error_album,error_date,success) VALUES ('','$randomString2','Album Creation was unsuccessful (Category could not be located)...','$file_name','','$date_time','3')");
}
}
} // 2nd foreach
}
} // 1st foreach
$date_time = date("Y-m-d H:i:s");
mysqli_query($conn,"UPDATE new_recent_batch_uses SET `batch_completed` = '$date_time' WHERE `error_ref` = '$randomString2'");
header("Location: admin_batch_upload.php?album_create_completed=1&completed=".$c."&folders=".$i."#images");
}
create_thumbs function -
function create_thumbs($conn, $albums_to_add, $choosen_files, $error_ref) {
set_time_limit(0);
$get_quality = mysqli_fetch_assoc(mysqli_query($conn, "SELECT `value` FROM `new_system_settings` WHERE `setting_id` = '31'"));
$img_quality = $get_quality['value'];
$get_resize = mysqli_fetch_assoc(mysqli_query($conn, "SELECT `value` FROM `new_system_settings` WHERE `setting_id` = '32'"));
$img_resize = $get_resize['value'];
session_start();
$dirname = $choosen_files;
chmod($dirname, 0777);
$todays_date = date("Y-m-d");
$date_time = date("Y-m-d H:i:s");
if($albums_to_add == ''){
mysqli_query($conn,"INSERT INTO new_upload_error_log (error_id,error_ref,error_type,error_image,error_album,error_date,success) VALUES ('','$error_ref','There was no album selected for this file','$choosen_files','$albums_to_add','$date_time','3')");
} else {
$check_end = substr($dirname, -1);
if($check_end == '/'){
$dirname = $choosen_files;
} else {
$dirname = $choosen_files.'/';
}
$images = glob($dirname."*.{JPG,jpg,PNG,png,gif}", GLOB_BRACE);
$filecount = count($images);
$arr_content = array();
$counti = 0;
foreach($images as $image) {
$counti++;
$percent = intval($counti/$filecount * 100);
$arr_content['percent'] = $percent;
$arr_content['message'] = $counti . " image(s) processed.";
$file = $image;
$data = $image;
$cut_name = substr($data, strpos($data, "/") + 1);
$cut_name = explode('/',$cut_name);
$cut_name = end($cut_name);
if (0 === strpos($cut_name, 'thb_')) {
mysqli_query($conn,"INSERT INTO new_upload_error_log (error_id,error_ref,error_type,error_image,error_album,error_date,success) VALUES ('','$error_ref','Compressed Image already exists in this file...','$newfile','$albums_to_add','$date_time','4')");
} else {
if (strpos($cut_name, 'thumb_') == false && strpos($cut_name, 'normal_') == false) {
if (strpos($cut_name, 'mini_') == false) {
$newfile = $dirname.'thb_'.$cut_name;
///unlink($newfile);
if (file_exists($newfile)) {
mysqli_query($conn,"INSERT INTO new_upload_error_log (error_id,error_ref,error_type,error_image,error_album,error_date,success) VALUES ('','$error_ref','Compressed Image already exists in this file...','$newfile','$albums_to_add','$date_time','4')");
} else {
$info = getimagesize($file);
list($width, $height) = getimagesize($file);
$new_width = $width * $img_resize / 100;
$new_height = $height * $img_resize / 100;
if ($info['mime'] == 'image/jpeg') $image = imagecreatefromjpeg($file);
elseif ($info['mime'] == 'image/gif') $image = imagecreatefromgif($file);
elseif ($info['mime'] == 'image/png') $image = imagecreatefrompng($file);
$image = imagecreatetruecolor($new_width, $new_height);
$photo = imagecreatefromjpeg($file);
imagecopyresampled($image, $photo, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
imagejpeg($image, $newfile, $img_quality);
$origional_image = $file;
$compressed_image = $newfile;
if (file_exists($compressed_image)) {
$query = mysqli_query($conn, "SELECT * FROM new_images WHERE alb_ref = '".$albums_to_add."' AND full_link = '".$origional_image."'");
if(mysqli_num_rows($query) > 0){
mysqli_query($conn,"INSERT INTO new_upload_error_log (error_id,error_ref,error_type,error_image,error_album,error_date,success) VALUES ('','$error_ref','This image already exists within this Album...','$compressed_image','$albums_to_add','$date_time','4')");
} else {
mysqli_query($conn,"INSERT INTO new_images (img_id,alb_ref,thumb_link,full_link,viewed_count,date_added) VALUES ('','$albums_to_add','$compressed_image','$origional_image','0','$todays_date')");
mysqli_query($conn,"UPDATE new_albums SET amount_of_files = amount_of_files + 1 WHERE album_ref = '$albums_to_add'");
}
} else {
mysqli_query($conn,"INSERT INTO new_upload_error_log (error_id,error_ref,error_type,error_image,error_album,error_date,success) VALUES ('','$error_ref','This image failed to compress...','$origional_image','$albums_to_add','$date_time','3')");
}
file_put_contents("tmp/" . session_id() . ".txt", json_encode($arr_content));
}
} else {
}
} else {
}
}
}
}
}
If anybody has any other solutions for me, that would be great? Even some advice on how I can work out the actual type of error I am getting. I am pretty sure it is a timeout error, because it happens on every attempt although on smaller folder structures with less files, the system works flawlessly.

Related

How to select image sized between 100-500 kb?

I have a short PHP code to help me display random images from a specific folder. But now it seems to select any image in any size. I want those selected images are between 100-500 kb. If it's less than 100 kb or over 500 kb, the function won't select and display it.
Could you please tell me how to modify this code? Probably need to add some function.
<?php $randomdir = dir('images/random');
$count = 1;
$pattern="/(gif|jpg|jpeg|png)/";
while($file = $randomdir->read()) {
$ext = pathinfo($file, PATHINFO_EXTENSION);
if (preg_match($pattern, $ext)) {
$imagearray[$count] = $file;
$count++;
}
}
$random = mt_rand(1, $count - 1);
echo '<img src="images/random/'.$imagearray[$random].'" alt />';
?>
Try this one We have to set 2 conditions
$min = 100; //KB
$max = 500; //KB
if($_FILES['myfile']['size'] < $min * 1024 || $_FILES['myfile']['size'] > $max * 1024){
echo 'error';
}
Try now
<?php
$dir_name = 'images/random/';
$pattern="/(gif|jpg|jpeg|png)/";
$min = 100;
$max = 500;
$imagearray = array();
$scanned_directory = array_diff(scandir($dir_name), array('..', '.'));
$count = count($scanned_directory);
$ids = array_keys($scanned_directory);
$s = TRUE;
$stop = $count;
while( ($s === TRUE) && ($stop >=0))
{
$random = mt_rand(0, $count - 1);
$full_path_to_file = $dir_name.$scanned_directory[$ids[$random]];
$ext = pathinfo($full_path_to_file, PATHINFO_EXTENSION);
$file_size_kb = round(filesize($full_path_to_file)/1024);
if (preg_match($pattern, $ext) && ($file_size_kb>=$min && $file_size_kb<=$max))
{
$s = FALSE;
echo '<img src="'.$full_path_to_file.'" alt />';
}
$stop--;
}
?>

Directory being deleted randomly by unknown script

I have set up a simple "Facebook" like timeline system for my friend to be able to upload statuses with images for his users to see. It seemed to all be working well although the file which stores the images keeps being deleted, and I can't seem to purposely cause the problem myself so I have no idea what is removing this directory?
I have added the upload/remove scripts below to see if anybody might be able to assist me here? I can't seem to find any part of the script which would delete the main image directory on its own?
PLEASE BARE IN MIND - This is still unfinished, and is nowhere near secure just yet, we are in testing phase and need to fix this problem before I can work on perfecting the system.
The main folder for storage of the images is post_images, this is the directory which is being deleted.
REMOVE DIR FUNCTION -
function rrmdir($dir) {
foreach(glob($dir . '/*') as $file) {
if(is_dir($file)) rrmdir($file); else unlink($file);
}
rmdir($dir);
}
DECLINE POSTS -
if(isset($_GET['decline_post'])){
$post_id = $conn->real_escape_string($_GET['decline_post']);
$getimagefolder = mysqli_fetch_assoc(mysqli_query($conn, "SELECT `post_image_folder` FROM `Pto6LsuQ_posts` WHERE `post_id` = '$post_id'"));
$image_folder = $getimagefolder['post_image_folder'];
mysqli_query($conn,"DELETE FROM `Pto6LsuQ_posts` WHERE `post_id` = '$post_id'");
$direc = 'post_images/'.$image_folder;
if (file_exists($direc)) {
rrmdir($direc);
} else {
}
header("Location: members_area.php");
}
DELETE POST -
if(isset($_GET['delete_post'])){
$post_id = $conn->real_escape_string($_GET['delete_post']);
$getimagefolder = mysqli_fetch_assoc(mysqli_query($conn, "SELECT `post_image_folder` FROM `Pto6LsuQ_posts` WHERE `post_id` = '$post_id'"));
$image_folder = $getimagefolder['post_image_folder'];
mysqli_query($conn,"DELETE FROM `Pto6LsuQ_posts` WHERE `post_id` = '$post_id'");
$direc = 'post_images/'.$image_folder;
if (file_exists($direc)) {
rrmdir($direc);
} else {
}
header("Location: members_area.php");
}
UPLOAD POST -
if(isset($_POST['new_post'])){
$post_status = $conn->real_escape_string($_POST['status']);
$user_id = $_SESSION['user_id'];
if(!empty($_FILES['images']['tmp_name'])){
$length = 9;
$search = true; // allow the loop to begin
while($search == true) {
$rand_image_folder = substr(str_shuffle("0123456789"), 0, $length);
if (!file_exists('../post_images/'.$rand_image_folder)) {
$search = false;
}
}
mkdir("../post_images/".$rand_image_folder);
foreach($_FILES['images']['tmp_name'] as $key => $tmp_name ){
$file_name = $key.$_FILES['images']['name'][$key];
$file_size = $_FILES['images']['size'][$key];
$file_tmp = $_FILES['images']['tmp_name'][$key];
$file_type = $_FILES['images']['type'][$key];
$check_file_type = substr($file_type, 0, strrpos( $file_type, '/'));
if($check_file_type !== 'image'){
header('Location: ../members_area.php?posterror=1');
}
$extensions = array("jpeg","jpg","png","JPEG","JPG","PNG");
$format = trim(substr($file_type, strrpos($file_type, '/') + 1));
if(in_array($format,$extensions) === false){
header('Location: ../members_area.php?posterror=1');
} else {
move_uploaded_file($file_tmp,"../post_images/".$rand_image_folder."/".$file_name);
$file = "../post_images/".$rand_image_folder."/".$file_name;
$cut_name = substr($file, strpos($file, "/") + 1);
$cut_name = explode('/',$cut_name);
$cut_name = end($cut_name);
$newfile = "../post_images/".$rand_image_folder."/thb_".$cut_name;
$info = getimagesize($file);
list($width, $height) = getimagesize($file);
$max_width = '350';
$max_height = '250';
//try max width first...
$ratio = $max_width / $width;
$new_width = $max_width;
$new_height = $height * $ratio;
//if that didn't work
if ($new_height > $max_height) {
$ratio = $max_height / $height;
$new_height = $max_height;
$new_width = $width * $ratio;
}
if ($info['mime'] == 'image/jpeg') $image = imagecreatefromjpeg($file);
elseif ($info['mime'] == 'image/gif') $image = imagecreatefromgif($file);
elseif ($info['mime'] == 'image/png') $image = imagecreatefrompng($file);
$image = imagecreatetruecolor($new_width, $new_height);
$photo = imagecreatefromjpeg($file);
imagecopyresampled($image, $photo, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
imagejpeg($image, $newfile, 70);
}
}
if($account_type < 4){
$post_public = 1;
} else {
$post_public = 0;
}
mysqli_query($conn,"INSERT INTO `Pto6LsuQ_posts`
(post_id,post_user_id,post_date_time,post_status,post_image_folder,post_likes,post_public_status)
VALUES ('','$user_id',NOW(),'$post_status','$rand_image_folder','0','$post_public')");
} else {
if($account_type < 4){
$post_public = 1;
} else {
$post_public = 0;
}
mysqli_query($conn,"INSERT INTO `Pto6LsuQ_posts`
(post_id,post_user_id,post_date_time,post_status,post_image_folder,post_likes,post_public_status)
VALUES ('','$user_id',NOW(),'$post_status','','0','$post_public')");
}
header('Location: ../members_area.php?posterror=2');
}

Blueimp Jquery File Upload S3 & Resize

I am using the Blueimp/jQuery-File-Uploader and the Amazon S3 plugin that is available for it and all is working out fine however I need to resize my images to be no more or less that 640px on the shortest side.
my current code is
global $s3;
if (isset($_REQUEST['_method']) && $_REQUEST['_method'] === 'DELETE') {
return "";
}
$upload = isset($_FILES['files']) ? $_FILES['files'] : null;
$info = array();
if ($upload && is_array($upload['tmp_name'])) {
foreach($upload['tmp_name'] as $index => $value) {
$fileTempName = $upload['tmp_name'][$index];
$file_name = (isset($_SERVER['HTTP_X_FILE_NAME']) ? $_SERVER['HTTP_X_FILE_NAME'] : $upload['name'][$index]);
$extension=end(explode(".", $file_name));
$rand = rand(1,100000000);
$sha1 = sha1($rand);
$md5 = md5($sha1);
$filename = substr($md5, 0, 8);
$fileName=$filename.".".$extension;
$fileName = $prefix.str_replace(" ", "_", $fileName);
$response = $s3->create_object($bucket, $fileName, array('fileUpload' => $fileTempName, 'acl' => AmazonS3::ACL_PUBLIC, 'meta' => array('keywords' => 'example, test'),));
if ($response->isOK()) {
$info[] = getFileInfo($bucket, $fileName);
} else {
// echo "<strong>Something went wrong while uploading your file... sorry.</strong>";
}
}
And I have written this bit of PHP however I am not sure as to how I can get the two working together.
$image = new Imagick('test2.jpg');
$imageprops = $image->getImageGeometry();
$w=$imageprops['width'];
$h=$imageprops['height'];
$edge = min($w,$h);
$ratio = $edge / 640;
$tWidth = ceil($w / $ratio);
$tHeight = ceil($h / $ratio);
if ($imageprops['width'] <= 640 && $imageprops['height'] <= 640) {
// don't upscale
} else {
$image->resizeImage($tWidth,$tHeight,imagick::FILTER_LANCZOS, 0.9, true);
}
$image->writeImage("test2-resized.jpg");
any help will be gratefully received, thanks
This is based on the assumption that all code in the OP's message was correct, and simply re-arranged it as requested.
Update: four upvotes (so far) seems to indicate the OP was correct not only regarding the code, but also regarding the magnitude of the issue. I do OSS as a matter of course, so by all means, let me know explicitly if this is of any interest to you so we can improve on this on github (any action is fine -- upvote the question, upvote the answer, post a comment, or any combination thereof).
function resize($imgName, $srcName)
{
$image = new Imagick($imgName);
$imageprops = $image->getImageGeometry();
$w=$imageprops['width'];
$h=$imageprops['height'];
$edge = min($w,$h);
$ratio = $edge / 640;
$tWidth = ceil($w / $ratio);
$tHeight = ceil($h / $ratio);
if ($imageprops['width'] <= 640 && $imageprops['height'] <= 640) {
return $imgName;
} else {
$image->resizeImage($tWidth,$tHeight,imagick::FILTER_LANCZOS, 0.9, true);
}
$extension=end(explode(".", $srcName));
// Change "/tmp" if you're running this on Windows
$tmpName=tempnam("/tmp", "resizer_").".".$extension;
$image->writeImage($tmpName);
return $tmpName
}
global $s3;
if (isset($_REQUEST['_method']) && $_REQUEST['_method'] === 'DELETE') {
return "";
}
$upload = isset($_FILES['files']) ? $_FILES['files'] : null;
$info = array();
if ($upload && is_array($upload['tmp_name'])) {
foreach($upload['tmp_name'] as $index => $value) {
$file_name = (isset($_SERVER['HTTP_X_FILE_NAME']) ? $_SERVER['HTTP_X_FILE_NAME'] : $upload['name'][$index]);
$fileTempName = resize($upload['tmp_name'][$index], $file_name);
$extension=end(explode(".", $file_name));
$rand = rand(1,100000000);
$sha1 = sha1($rand);
$md5 = md5($sha1);
$filename = substr($md5, 0, 8);
$fileName=$filename.".".$extension;
$fileName = $prefix.str_replace(" ", "_", $fileName);
$response = $s3->create_object($bucket, $fileName, array('fileUpload' => $fileTempName, 'acl' => AmazonS3::ACL_PUBLIC, 'meta' => array('keywords' => 'example, test'),));
if ($response->isOK()) {
$info[] = getFileInfo($bucket, $fileName);
} else {
// `echo "<strong>Something went wrong while uploading your file... sorry.</strong>";`
}
unlink($fileTempName);
}

Issues with PHP image upload

I've been creating a HTML5 Drag & Drop image up-loader. All is good with the Javascript side of things however the PHP is driving me crazy!
I've been able to create a script that successfully places a image in a folder upon the drop of an image, however once it tries to create a thumb nail for the image and place the image link into the users db table it all goes to pot. I've sat here for hours on end, trying and trying to no avail, so i believe as it is now just about 3am GMT i should admit defeat and ask for a little help.
The JavaScript:
$(function(){
var dropbox = $('#dropbox'),
message = $('.message', dropbox);
dropbox.filedrop({
paramname:'pic',
maxfiles: 5,
maxfilesize: 200,
url: 'uploadCore.php',
uploadFinished:function(i,file,response){
$.data(file).addClass('done');
},
error: function(err, file) {
switch(err) {
case 'BrowserNotSupported':
showMessage('Your browser does not support HTML5 file uploads!');
break;
case 'TooManyFiles':
alert('Too many files!');
break;
case 'FileTooLarge':
alert(file.name+' is too large! Please upload files up to 200mb.');
break;
default:
break;
}
},
beforeEach: function(file){
if(!file.type.match(/^image\//)){
alert('Only images are allowed!');
return false;
}
},
uploadStarted:function(i, file, len){
createImage(file);
},
progressUpdated: function(i, file, progress) {
$.data(file).find('.progress').width(progress);
}
});
var template = '<div class="preview">'+
'<span class="imageHolder">'+
'<img />'+
'<span class="uploaded"></span>'+
'</span>'+
'<div class="progressHolder">'+
'<div class="progress"></div>'+
'</div>'+
'</div>';
function createImage(file){
var preview = $(template),
image = $('img', preview);
var reader = new FileReader();
image.width = 100;
image.height = 100;
reader.onload = function(e){
image.attr('src',e.target.result);
};
reader.readAsDataURL(file);
message.hide();
preview.appendTo(dropbox);
$.data(file,preview);
}
function showMessage(msg){
message.html(msg);
}
});
Now for the PHP:
<?php
// db connection
include("db-info.php");
$link = mysql_connect($server, $user, $pass);
if(!mysql_select_db($database)) die(mysql_error());
include("loadsettings.inc.php");
//$upload_dir = 'pictures/';
$allowed_ext = array('jpg','jpeg','png','gif');
if(strtolower($_SERVER['REQUEST_METHOD']) != 'post'){
exit_status('Error! Wrong HTTP method!');
}
if(array_key_exists('pic',$_FILES) && $_FILES['pic']['error'] == 0 ){
if (isset($_SESSION["imagehost-user"]))
{
$session = true;
$username = $_SESSION["imagehost-user"];
$password = $_SESSION["imagehost-pass"];
$q = "SELECT id FROM `members` WHERE (username = '$username') and (password = '$password')";
if(!($result_set = mysql_query($q))) die(mysql_error());
$number = mysql_num_rows($result_set);
if (!$number) {
session_destroy();
$session = false;
}else {
$row = mysql_fetch_row($result_set);
$loggedId = $row[0];
}
}
$date = date("d-m-y");
$lastaccess = date("y-m-d");
$ip = $_SERVER['REMOTE_ADDR'];
$type = "public";
$pic = $_FILES['pic'];
$n = $pic;
$rndName = md5($n . date("d-m-y") . time()) . "." . get_extension($pic['name']);
$upload_dir = "pictures/" . $rndName;
move_uploaded_file($pic['tmp_name'], $upload_dir.$pic['name']);
// issues starts here
$imagePath = $upload_dir;
$img = imagecreatefromunknown($imagePath);
$mainWidth = imagesx($img);
$mainHeight = imagesy($img);
$a = ($mainWidth >= $mainHeight) ? $mainWidth : $mainHeight;
$div = $a / 150;
$thumbWidth = intval($mainWidth / $div);
$thumbHeight = intval($mainHeight / $div);
$myThumb = imagecreatetruecolor($thumbWidth, $thumbHeight);
imagecopyresampled($myThumb, $img, 0, 0, 0, 0, $thumbWidth, $thumbHeight, $mainWidth, $mainHeight);
$thumbPath = "thumbnails/" . basename($imagePath);
imagejpeg($myThumb, $thumbPath);
$details = intval(filesize($imagePath) / 1024) . " kb (" . $mainWidth . " x " . $mainHeight . ")" ;
$id = md5($thumbPath . date("d-m-y") . time());
$q = "INSERT INTO `images`(id, userid, image, thumb, tags, details, date, access, type, ip)
VALUES('$id', '$loggedId', '$imagePath', '$thumbPath', '$tags', '$details', '$date', '$lastaccess', 'member-{$type}', '$ip')";
if(!($result_set = mysql_query($q))) die(mysql_error());*/
exit_status('File was uploaded successfuly!');
// to here
$result = mysql_query("SELECT id FROM `blockedip` WHERE ip = '$ip'");
$number = mysql_num_rows($result);
if ($number) die(""); // blocked IP message
function imagecreatefromunknown($path) {
$exten = get_extension($path);
switch ($exten) {
case "jpg":
$img = imagecreatefromjpeg($path);
break;
case "gif":
$img = imagecreatefromgif($path);
break;
case "png":
$img = imagecreatefrompng($path);
break;
}
return $img;
}
}
exit_status('Something went wrong with your upload!');
// Helper functions
function exit_status($str){
echo json_encode(array('status'=>$str));
exit;
}
function get_extension($file_name){
$ext = explode('.', $file_name);
$ext = array_pop($ext);
return strtolower($ext);
}
?>
It seems you pass wrong path to the imagecreatefromunknown() function. You pass $imagePath that equals $upload_dir, but your image destination is $upload_dir.$pic['name']

Image upload without register_globals

I use a image upload script which has stopped working now that my host has turned register_globals off. However, I don't know how do make it work without it. I'd be glad if you could help me out. Here's the code:
$uploadedfile = $_FILES['photo']['tmp_name'];
$src = imagecreatefromjpeg($uploadedfile);
// get the date from EXIF data
$exif = exif_read_data($uploadedfile, 0, true);
foreach ($exif as $key => $section) {
foreach ($section as $name => $val) {
if ($name == 'DateTimeOriginal') {
$the_filename = explode(" ", $val);
$the_filenamedate = str_replace(":", "", $the_filename[0]);
$the_filenametime = str_replace(":", "", $the_filename[1]);
$newfilename = $the_filenamedate."-".$the_filenametime.".jpg";
$the_datetime = explode(" ", $val);
$the_date = str_replace(":", "-", $the_datetime[0]);
$the_time = $the_datetime[1];
$datetime = $the_date." ".$the_time;
$exif_db = 'y';
}
}
}
// use current date and time if no exif data
if (empty($newfilename)) {
$newfilename = date("Ymd-His").".jpg";
$datetime = date("Y-m-d H:i:s");
$exif_db = 'n';
}
// resize if necessary
list($width,$height) = getimagesize($uploadedfile);
if ($resize_it == 'y') {
if ($width > $maxwidth) {
$newwidth = $maxwidth;
$newheight = ($height/$width)*$newwidth;
} else {
$newwidth = $width;
$newheight = ($height/$width)*$newwidth;
}
} else {
$newwidth = $width;
$newheight = $height;
}
$tmp = imagecreatetruecolor($newwidth,$newheight);
imagecopyresampled($tmp,$src,0,0,0,0,$newwidth,$newheight,$width,$height);
$filename = $dirpath.$gal_id."/".$newfilename;
imagejpeg($tmp,$filename,100);
// create thumbnail
$uploadedthumb = $_FILES['photo']['tmp_name'];
$srcthumb = imagecreatefromjpeg($uploadedthumb);
list($widththumb,$heightthumb) = getimagesize($uploadedthumb);
if ($widththumb > $heightthumb) {
$newheightthumb = 100;
$newwidththumb = ($widththumb/$heightthumb)*$newheightthumb;
} elseif ($widththumb == $heightthumb) {
$newheightthumb = 100;
$newwidththumb = 100;
} elseif ($widththumb < $heightthumb) {
$newwidththumb = 100;
$newheightthumb = ($heightthumb/$widththumb)*$newwidththumb;
} else {
$newheightthumb = 100;
$newwidththumb = ($widththumb/$heightthumb)*$newheightthumb;
}
$tmpthumb = imagecreatetruecolor($newwidththumb,$newheightthumb);
imagecopyresampled($tmpthumb,$srcthumb,0,0,$src_top,$src_left,$newwidththumb,$newheightthumb,$widththumb,$heightthumb);
$thumbname = $dirpath.$gal_id."/zth_".$newfilename.".jpg";
imagejpeg($tmpthumb,$thumbname,100);
// free memory, destroying the source's and the pic's canvas
imagedestroy($srcthumb);
imagedestroy($tmpthumb);
imagedestroy($src);
imagedestroy($tmp);
Thanks in advance!
Use the $_POST array to read posted form fields. A field named emil will have the value in the PHP variable $_POST['emil'], not in $emil. You have to change all instances where you read form fields.
The same applies for variables in the querystring, which is now found in $_GET, cookies in $_COOKIE and session variables in $_SESSION.

Categories