How do you make thumbnails on upload with phpthumb? - php

I'm having a very problematic error with phpthumb: http://phpthumb.gxdlabs.com/
So basically, I have a form which uploads a profile picture. The uploading seems to work because it uploads the image in the directory. The problem is that it doesn't generate the thumbnails but I'm sure that all the variables and names are correct. It gives me the following error. Specifically 'Image file not found':
Fatal error: Uncaught exception 'Exception' with message 'Image file not found: ����' in {PATH}\phpthumb\ThumbBase.inc.php:193 Stack trace: #0 {PATH}\phpthumb\ThumbBase.inc.php(172): ThumbBase->triggerError('Image file not ...') #1 {PATH}\phpthumb\ThumbBase.inc.php(110): ThumbBase->fileExistsAndReadable() #2 {PATH}\phpthumb\GdThumb.inc.php(96): ThumbBase->__construct('??????JFIF?????...', false) #3 G:\EasyPHP\www\YourSlab\phpthumb\ThumbLib.inc.php(127): GdThumb->__construct('??????JFIF?????...', Array, false) #4 {PATH}\edit_profile.php(74): PhpThumbFactory::create('??????JFIF?????...') #5 {PATH}\edit_profile.php(80): generateThumbnail->createthumbnail(25) #6 {PATH}\edit_profile.php(118): set_profile_info('Mico Abrina', '1', 'asdf', 'asdf', '', 'asdf', 'asdf', '', '05', '4', '1996', 'G:\EasyPHP\tmp\...') #7 {main} thrown in {PATH}\phpthumb\ThumbBase.inc.php on line 193
I think its because I'm generating the thumbnails right after uploading it. How do I make it work?
<?php
//upload images
if (file_exists($profile_pic)) {
$src_size = getimagesize($profile_pic);
if ($src_size['mime'] === 'image/jpeg'){
$src_img = imagecreatefromjpeg($profile_pic);
} else if ($src_size['mime'] === 'image/png') {
$src_img = imagecreatefrompng($profile_pic);
} else if ($src_size['mime'] === 'image/gif') {
$src_img = imagecreatefromgif($profile_pic);
} else {
$src_img = false;
}
if ($src_img !== false) {
$md5sessionid = md5($_SESSION['user_id'].'asdf');
imagejpeg($src_img, "profile_pic/$md5sessionid.jpg");
//end of uploading images
//image thumbnail creation class
class generateThumbnail {
public function createthumbnail($size) {
$md5sessionidsecret = md5($_SESSION['user_id'].'asdf');
$md5sessionidthumb = md5($md5sessionidsecret.''.$size);
$path_to_thumb_pic = 'profile_pic/'.$md5sessionidthumb.'.jpg';
$profile_pic = file_get_contents('profile_pic/'.$md5sessionidsecret.'.jpg');
$thumb_profile_pic = PhpThumbFactory::create($profile_pic);
$thumb_profile_pic->adaptiveResize($size, $size);
$thumb_profile_pic->save($path_to_thumb_pic);
}
}
//make the thumbnails
$createThumbnail = new generateThumbnail();
$createThumbnail->createthumbnail(25);
$createThumbnail->createthumbnail(75);
$createThumbnail->createthumbnail(175);
}
}
?>

It appears that PhpThumbFactory::create() takes a file path as its first argument, unless you specify true for the third isDataStream argument. That is why you are getting the strange output in the exception where it says Image File Not Found.
You could do a few things to fix it:
// Either skip the file_get_contents call and pass the file path directly
$thumb_profile_pic = PhpThumbFactory::create('profile_pic/'.$md5sessionidsecret.'.jpg');
// or set the 3rd parameter isDataStream to true
$profile_pic = file_get_contents('profile_pic/'.$md5sessionidsecret.'.jpg');
$thumb_profile_pic = PhpThumbFactory::create($profile_pic, array(), true);

Related

PHP Fatal error: Uncaught ValueError: Path cannot be empty on PHP8

This code is attached to a Gravity form, there is a file upload field on the form, and this code (although poorly written) grabs each file from the file upload field and uploads it to the server. My problem is, now that we have upgraded to PHP8, it's throwing an error:
//$entry[35] is the file upload field in the form.
//This grabs the uploaded file whatever it may be, and uploads it to the server
$newest_again = str_replace('[',"",$entry[35]);
$newest_final = str_replace(']',"",$newest_again);
$newest_fin = str_replace('"',"",$newest_final);
$entryArr = explode(",",$newest_fin);
if(!empty($entry[35])){
if(count($entryArr) > 1){
//multiple files have been added to the upload field
$count = 0;
$token = "";
$fileArr = array();
$binArr = array();
$extens = array();
foreach($entryArr as $file_entry){
//processing string to grab the file name only for each file
$new = str_replace('\\',"",$file_entry);
$new_again = str_replace('[',"",$new);
$new_final = str_replace(']',"",$new_again);
$new_fin = str_replace('"',"",$new_final);
$binFile = file_get_contents($new_fin);
$ext = pathinfo($new_fin, PATHINFO_EXTENSION);
array_push($fileArr, $new_fin);
array_push($binArr, $binFile);
array_push($extens, $ext);
}
//upload each file to server
while($count < (count($fileArr))){
$upload = curlUpload("/uploads.json", $binArr[$count], 'screenshot-'.$count.".".$extens[$count], $fileArr[$count],$token); // Attachments will have the prettyname screenshot.[$ext]
if($token == ""){
$token = $upload->upload->token;
}
else{
$token = $token;
}
$count ++;
}
print_r($uploads);
}
else{
//just one file was added to the form, so upload it
$fileArr = array();
$placeholder ="";
$new = str_replace('\\',"",$entry[35]);
$new_again = str_replace('[',"",$new);
$new_final = str_replace(']',"",$new_again);
$new_fin = str_replace('"',"",$new_final);
$binaryFile = file_get_contents($new_fin);
$ext = pathinfo($new_fin, PATHINFO_EXTENSION); // Upload field ID
$upload = curlUpload("/uploads.json", $binaryFile, 'screenshot.'.$ext, $new_fin, $placeholder); // Attachments will have the prettyname screenshot.[$ext]
$token = $upload->upload->token;
}
}
The error is:
PHP Fatal error: Uncaught ValueError: Path cannot be empty in /wp-content/themes/blankslate/functions.php:31483
Stack:
#0 /wp-content/themes/blankslate/functions.php(31483): file_get_contents('')
This error is ONLY thrown if a file is not added to the upload field on the form. If a file or files are added, the error is not thrown. It seems to be calling file_get_contents(); and throwing the error message when nothing has been added to the upload field in the form. This is the line that is throwing the error message:
$binFile = file_get_contents($new_fin);
I wrapped everything in this block:
if(!empty($entry[35])){
So that this code ONLY runs if the file upload field is not empty, but it is still throwing the error message even when no files are added to the file upload field in the form.
Is there anything I can add to this code that will prevent the error?

Form upload errors after updating to PHP version 7.3.11 [duplicate]

This question already has answers here:
Reference - What does this error mean in PHP?
(38 answers)
Fatal error: Uncaught ArgumentCountError: Too few arguments to function
(6 answers)
Closed 2 years ago.
I have a form that was working normally until our host updated the PHP version to 7.3.11. Now when you try to submit to the form it gives this error message:
Fatal error: Uncaught ArgumentCountError: Too few arguments to
function sl_upload(), 2 passed in
/nfs/c07/h03/mnt/113634/domains/myurl.com/html/appLms/modules/question/class.upload.php
on line 331 and exactly 3 expected in
/nfs/c07/h03/mnt/113634/domains/myurl.com/html/lib/lib.upload.php:74
Stack trace: #0
/nfs/c07/h03/mnt/113634/domains/myurl.com/html/appLms/modules/question/class.upload.php(331):
sl_upload('/var/tmp/phpU0P...', '/appLms/test/2_...') #1
/nfs/c07/h03/mnt/113634/domains/myurl.com/html/appLms/lib/lib.test.php(1106):
Upload_Question->storeAnswer(Object(Track_Test), Array, '1') #2
/nfs/c07/h03/mnt/113634/domains/myurl.com/html/appLms/modules/test/do.test.php(1208):
PlayTestManagement->storePage('1', '1') #3
/nfs/c07/h03/mnt/113634/domains/myurl.com/html/appLms/modules/test/do.test.php(592):
showResult(Object(Learning_Test), 29) #4
/nfs/c07/h03/mnt/113634/domains/myurl.com/html/appLms/class.module/learning.test.php(309):
in /nfs/c07/h03/mnt/113634/domains/myurl.com/html/lib/lib.upload.php
on line 74
I didn't change any of the code. The only thing that changed was the PHP version. As a result, I'm not even sure how to start fixing this.
Here's what's on class.upload.php > line 331
sl_open_fileoperations();
if(!sl_upload($_FILES['quest']['tmp_name'][$this->id], $path.$savefile)) {
$savefile = Lang::t('_QUEST_ERR_IN_UPLOAD');
}
sl_close_fileoperations();
} else {
$savefile = Lang::t('_QUEST_ERR_IN_UPLOAD');
}
}
...and here's what's on lib.upload.php > Line 74
function sl_upload( $srcFile, $dstFile, $file_ext) {
$uploadType = Get::cfg('uploadType', null);
// check if the mime type is allowed by the whitelist
// if the whitelist is empty all types are accepted
require_once(_lib_.'/lib.mimetype.php');
$upload_whitelist =Get::sett('file_upload_whitelist', 'rar,exe,zip,jpg,gif,png,txt,csv,rtf,xml,doc,docx,xls,xlsx,ppt,pptx,odt,ods,odp,pdf,xps,mp4,mp3,flv,swf,mov,wav,ogg,flac,wma,wmv,jpeg');
$upload_whitelist_arr =explode(',', trim($upload_whitelist, ','));
if (!empty($upload_whitelist_arr)) {
$valid_ext = false;
$ext=strtolower(substr(strrchr($dstFile, "."), 1));
if($ext!=""){
$file_ext =strtolower(substr(strrchr($dstFile, "."), 1));
}
foreach ($upload_whitelist_arr as $k=>$v) { // remove extra spaces and set lower case
$ext =trim(strtolower($v));
$mt =mimetype($ext);
if ($mt) { $mimetype_arr[]=$mt; }
getOtherMime($ext, $mimetype_arr);
if ($ext == $file_ext) {
$valid_ext =true;
}
}
$mimetype_arr = array_unique($mimetype_arr);
if ( class_exists('finfo') && method_exists('finfo', 'file')) {
$finfo =new finfo(FILEINFO_MIME_TYPE);
$file_mime_type =$finfo->file($srcFile);
}
else {
$file_mime_type =mime_content_type($srcFile);
}
if (!$valid_ext || !in_array($file_mime_type, $mimetype_arr)) {
return false;
}
}
$dstFile =stripslashes($dstFile);
if( $uploadType == "ftp" ) {
return sl_upload_ftp( $srcFile, $dstFile );
} elseif( $uploadType == "cgi" ) {
return sl_upload_cgi( $srcFile, $dstFile );
} elseif( $uploadType == "fs" || $uploadType == null ) {
return sl_upload_fs( $srcFile, $dstFile );
} else {
$event = new \appCore\Events\Core\FileSystem\UploadEvent($srcFile, $dstFile);
\appCore\Events\DispatcherManager::dispatch(\appCore\Events\Core\FileSystem\UploadEvent::EVENT_NAME, $event);
unlink($srcFile);
return $event->getResult();
}
}
Based on that I'm not sure what to change and I don't want to break what was working before.
All the rest of the website is working normally, including PHP functions like logging in. Thanks in advance for any pointers.
Try replacing:
sl_upload($_FILES['quest']['tmp_name'][$this->id], $path.$savefile)
with:
sl_upload($_FILES['quest']['tmp_name'][$this->id], $path.$savefile, null);
Explanation: the sl_upload function is expecting 3 arguments, and you're passing only 2.
Before PHP 7.1, this only triggered a warning, but since then it's generating a Fatal Error instead.
Since it worked fine for you before (although, it must have triggered a Warning, which probably got logged somewhere unless your error_reporting is very lax), passing null as the third argument should produce the same outcome as it used to.
It would, however, be a better idea to figure out what that function argument is supposed to be used for, as it's marked as required (no default value).

How to bypass "PHPExcel_Calculation_Exception" when creating CSV from excel sheet?

<?php
require_once 'PHPExcel/PHPExcel.php';
$downloadedFileName = "sheet.xls";
set_time_limit(0);
if (file_exists($downloadedFileName)) {
unlink($downloadedFileName);
}
$spreadsheet_url="Google Sheet with 4 tabs URL goes here";
file_put_contents($downloadedFileName,file_get_contents($spreadsheet_url));
if (file_exists($downloadedFileName)) {
$inputFileType = PHPExcel_IOFactory::identify($downloadedFileName);
$objReader = PHPExcel_IOFactory::createReader($inputFileType);
$objPHPExcelReader = $objReader->load($downloadedFileName);
$loadedSheetNames = $objPHPExcelReader->getSheetNames();
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcelReader, 'CSV');
foreach($loadedSheetNames as $sheetIndex => $loadedSheetName) {
$objWriter->setSheetIndex($sheetIndex);
$objWriter->save($loadedSheetName.'.csv');
}
}
else{
echo "File not found";
}
?>
This gives an error :
Fatal error: Uncaught exception 'PHPExcel_Calculation_Exception' with
message 'ArticulosQueNoSonKARE!A1 -> internal error' in
D:\xampp\htdocs\xlstocsv\PHPExcel\PHPExcel\Cell.php:291 Stack trace: #0
D:\xampp\htdocs\xlstocsv\PHPExcel\PHPExcel\Worksheet.php(2492): PHPExcel_Cell-
>getCalculatedValue() #1
D:\xampp\htdocs\xlstocsv\PHPExcel\PHPExcel\Writer\CSV.php(142):
PHPExcel_Worksheet->rangeToArray('A1:M1', '', true) #2
D:\xampp\htdocs\xlstocsv\index.php(30): PHPExcel_Writer_CSV-
>save('ArticulosQueNoS...') #3 {main} thrown in
D:\xampp\htdocs\xlstocsv\PHPExcel\PHPExcel\Cell.php on line 291
I can figureout that its because of some cells containing formulas..But I need to take that value from the cell.
I have no edit permission to modify and edit those cells. I need this script running as a chrone job.. Ihave done with the other part.
Please help.
Thank you

PDF to Images generate

I have PDF with 25 pages, I want to convert it into images with all pages.
My code:
First I have found number of pages.
$tmpfname= 'test_pdf.pdf';
$path = "/var/www/my_path";
$numberOfPages = $this->count_pages($tmpfname);
$numberOfPages = intval($numberOfPages); // Number of pages eg.25
Loop for convert pdf to images
for($i=0;$i<=$numberOfPages;$i++){
$im = new imagick( $tmpfname.'['.$i.']' );
$im->setCompression(Imagick::COMPRESSION_JPEG);
$im->resizeImage('1024','800', Imagick::FILTER_UNDEFINED, 0.9, true);
$im->setCompressionQuality(100);
$im->setImageFormat('jpeg');
$im->writeImage($path.'/'.$i.'.jpg');
$im->clear();
$im->destroy();
}
Function for find number of pages
function count_pages($pdfname) {
$pdftext = file_get_contents($pdfname);
$num = preg_match_all("/\/Page\W/",$pdftext, $dummy);
return $num;
}
PDF uploaded ok, and also converted images from PDF. But got this type of error after completed process:
Fatal error: Uncaught exception 'ImagickException' with message
'Postscript delegate failed /var/www/php/flipbook/uploads/flipbooks/61/test_pdf.pdf':
# error/pdf.c/ReadPDFImage/663' in /var/www/php/flipbook/application/controllers/admin/flipbooks.php:83
Stack trace: #0 /var/www/php/flipbook/application/controllers/admin/flipbooks.php(83):
Imagick->__construct('/var/www/php/fl...')
#1 [internal function]: Flipbooks->create()
#2 /var/www/php/flipbook/system/core/CodeIgniter.php(359): call_user_func_array(Array, Array)
#3 /var/www/php/flipbook/index.php(210): require_once('/var/www/php/fl...')
#4 {main} thrown in /var/www/php/flipbook/application/controllers/admin/flipbooks.php on line 83
Any buddy can help me very appreciate...
If nothing else, you have an off by one error:
for($i=0;$i<=$numberOfPages;$i++){
//..
}
This attempts to print numberOfPages + 1 pages as the index starts at zero.
I got the perfect solution from here
My new code
$tmpfname= 'test_pdf.pdf';
$path = "/var/www/my_path";
$numberOfPages = $this->count_pages($tmpfname);
$numberOfPages = intval($numberOfPages); // Number of pages eg.25
// Saving every page of a PDF separately as a JPG thumbnail
$images = new Imagick("test_pdf.pdf");
foreach($images as $i=>$image) {
// Providing 0 forces thumbnail Image to maintain aspect ratio
$image->thumbnailImage(1024,0);
$image->writeImage($path.'/'.$i.'.jpg');
}
$images->clear();
function count_pages($pdfname) {
$pdftext = file_get_contents($pdfname);
$num = preg_match_all("/\/Page\W/",$pdftext, $dummy);
return $num;
}

pdf generation not working in framework Zend

I have a script that generates a PDF in Zend. I copied the script from converting image to pdf to another directory on the server. I now get the error:
Fatal error: Uncaught exception 'Zend_Pdf_Exception' with message 'Cannot create image resource.
File not found.' in /kalendarz/Zend/Pdf/Resource/ImageFactory.php:38
Stack trace:
#0 /kalendarz/Zend/Pdf/Image.php(124): Zend_Pdf_Resource_ImageFactory::factory('data/0116b4/cro...')
#1 /kalendarz/cms.php(56): Zend_Pdf_Image::imageWithPath('data/0116b4/cro...')
#2 {main} thrown in /kalendarz/Zend/Pdf/Resource/ImageFactory.php on line 38
Code of website, example link to image (http://tinyurl.com/8srbfza):
else if($_GET['action']=='generate') {
//1 punkt typograficzny postscriptowy (cyfrowy) = 1/72 cala = 0,3528 mm
function mm_to_pt($size_mm) {
return $size_mm/0.3528;
}
require_once("Zend/Pdf.php");
$pdf = new Zend_Pdf();
$page_w = mm_to_pt(100);
$page_h = mm_to_pt(90);
$page = $pdf->newPage($page_w.':'.$page_h.':');
$pdf->pages[] = $page;
$imagePath= 'data/'.$_GET['id'].'/crop_'.$_GET['id'].'.jpg'; //to nie jest miniaturka
$image = Zend_Pdf_Image::imageWithPath($imagePath);
$left = mm_to_pt(0);
$right = mm_to_pt(100);
$top = mm_to_pt(90);
$bottom = mm_to_pt(0);
$page->drawImage($image, $left, $bottom, $right, $top);
$pdfData = $pdf->render();
header("Content-Disposition: inline; filename=".$_GET['id'].".pdf");
header("Content-type: application/x-pdf");
echo $pdfData;
die();
}
Zend_Pdf_Image::imageWithPath expects a valid file and uses is_file function call to check the file existence.
First of all, use absolute path to the image, instead of using the relative one. You can specify the absolute path by referring to your APPLICATION_PATH. For example,
APPLICATION_PATH . '/../public/data
If APPLICATION_PATH is not already defined in your code, paste this code in your public/index.php
defined('APPLICATION_PATH')
|| define('APPLICATION_PATH', realpath(dirname(__FILE__) . '/../application'));
Then, check if 'data/'.$GET['id'].'/crop'.$_GET['id'].'.jpg' exists. Also, check if the file has proper permissions to be accessed by PHP.
Note : Use the Zend request object instead of the $_GET.
Use an absolute path:
$imagePath = '/kalendarz/data/'.$_GET['id'].'/crop_'.$_GET['id'].'.jpg';
or:
$imagePath = APPLICATION_PATH.'/../data/'.$_GET['id'].'/crop_'.$_GET['id'].'.jpg';
you might also want to put some validation on $_GET['id'].

Categories