PHPExcel Zip extension errors - can't produce Excel file - php

Overview
I'm trying to directly download an Excel spreadsheet created using PHPExcel. I don't have server-level access so I can't install or enable mods (such as the Zip module).
The data is a guestlist for an event.
Code
<?php
if(isset($_GET["event_id"])&&
!empty($_GET["event_id"])){
//Include PHPExcel, Excel2007, classes
require_once("inc/PHPExcel/PHPExcel.php");
require_once("inc/PHPExcel/PHPExcel/Writer/Excel2007.php");
require_once("inc/classes.php");
//Zip not installed - change settings to use local compression
PHPExcel_Settings::setZipClass(PHPExcel_Settings::PCLZIP);
//Get event data
$event_id = intval($_GET["event_id"]);
$event = new Event($event_id);
$guests = $event->getGuests();
//Create new PHPExcel object
$spreadsheet = new PHPExcel();
//Add data
$spreadsheet->setActiveSheetIndex(0);
$spreadsheet->getActiveSheet()->SetCellValue("B2", "TMC Gateway");
$spreadsheet->getActiveSheet()->SetCellValue("B3", "Event register");
$spreadsheet->getActiveSheet()->SetCellValue("B5", "Name");
$spreadsheet->getActiveSheet()->SetCellValue("C5", "Member/Guest");
$spreadsheet->getActiveSheet()->SetCellValue("D5", "Checkin Time");
foreach($guests as $guest){
if($guest["degree"]=="guest"){
$arr[] = [$guest["name1"]." ".$guest["name2"], "Guest", $guest["checkintime"]];
} else {
$arr[] = [trim($guest["name2"]), "Member", $guest["checkintime"]];
}
}
$currentCell = 6;
foreach($arr as $a){
$spreadsheet->getActiveSheet()->SetCellValue("B$currentCell",$a[0]);
$spreadsheet->getActiveSheet()->SetCellValue("C$currentCell",$a[1]);
$spreadsheet->getActiveSheet()->SetCellValue("D$currentCell",$a[2]);
$currentCell++;
}
//Rename sheet
$spreadsheet->getActiveSheet()->setTitle("TMC Gateway");
//Open writer
$writer = new PHPExcel_Writer_Excel2007($spreadsheet);
//Set headers and force download
header("Content-type: application/vnd.ms-excel");
header("Content-Disposition: attachment;filename=\"TMC_Gateway_Attendees-".$event_id.".xls\"");
$writer->save("php://output");
//Kill script
exit;
}
Issue
When processing originally and opening the file, I saw this error:
Fatal error: Class 'ZipArchive' not found in /home/loqui/public_html/doorapp/inc/PHPExcel/PHPExcel/Writer/Excel2007.php on line 227
I realised this is probably because the Zip module was either not installed or not enabled, so I followed these instructions at Class 'ZipArchive' not found error while using PHPExcel:
If you don't have ZipArchive installed/enabled for your PHP, and can't enable it yourself, then you can use
PHPExcel_Settings::setZipClass(PHPExcel_Settings::PCLZIP);
However, now when opening the file, this error appears:
Fatal error: Uncaught exception 'PHPExcel_Writer_Exception' with message 'Error zipping files : PCLZIP_ERR_READ_OPEN_FAIL (-2) : Unable to open temporary file '/tmppclzip-56df08ee0384c.tmp' in binary write mode' in /home/loqui/public_html/doorapp/inc/PHPExcel/PHPExcel/Shared/ZipArchive.php:108
Stack trace:
#0 /home/loqui/public_html/doorapp/inc/PHPExcel/PHPExcel/Writer/Excel2007.php(278): PHPExcel_Shared_ZipArchive->addFromString('_rels/.rels', '<?xml version="...')
#1 /home/loqui/public_html/doorapp/xls.php(66): PHPExcel_Writer_Excel2007->save('php://output')
#2 {main}
thrown in /home/loqui/public_html/doorapp/inc/PHPExcel/PHPExcel/Shared/ZipArchive.php on line 108
Question
As I don't have the Zip module enabled, and seemingly limited permissions in the working folder, how can I make this script download the correctly created Excel file?

If you are going to continue using PCLZIP, I would recommend checking the tmp directory that it is attempting to write to and see what user that directory is assigned to. More than likely Apache does not have write access to that tmp directory and thus is failing to write files inside of it. I am struggling with a similar problem on the ZipArchive front, but if you have sufficient permissions chown -R user:user foldername might alleviate your write issues.

Related

OCR wrapper for php

I am using this for ocr. This is wrapper for Tesseract ocr(I previosly installed Tesseract itself).
At first i dowloaded it via composer and followed examples in repo and also several posts on SO itself. And all can show is in network tab failed to load response data.
My alternate approaches is that i tried downloading repo itself, then tried to call it from my index.php which for test purposes is situated in same folder where class TesseractOCR is. I tried with images in repo and also tried with black letters on white background images with simple text.
This SO post looks promising, but i'm unsure where OP's file with example code is residing...
use thiagoalessio\TesseractOCR\TesseractOCR;
//or//require "TesseractOCR.php";//if it's in the same dir as test.php
$content = new TesseractOCR('text.png');
$text = $content->run();
echo $text;
Did i miss something obvious? Any help is appreciated.
EDIT1: I tried using in win powershell cli. By putting text.png in directory where tesseract is installed, then calling shell with administrator privileges, subsequently typing in it tesseract text.png output which creates output.txt in same directory with recognized text from that image.
So tesseract its working, my implementation with php wrapper is not.
EDIT2:
Forgot to add, page itself shows:
This page isn’t working
localhost is currently unable to handle this request.
HTTP ERROR 500
Not sure why it happens.
Edit3:
My code:
try{
//use thiagoalessio\TesseractOCR\TesseractOCR;
require "./vendor/thiagoalessio/tesseract_ocr/src/TesseractOCR.php";
echo $temp;//It's value is set in TesseractOCR.php
$content = new TesseractOCR('text1.png');
$text = $content->run();
echo $text;
}
catch(Exception $e) {
echo 'Message: ' .$e->getMessage();
}
Value set in $temp variable is visible through state file path, so why TesseractOCRclass itself isn't?
Edit4:
Even if i put absolute path to TesseractOCR.php which holds class, in include statement, it doesn't work.
It throws this error:
Fatal error: Uncaught Error: Class 'TesseractOCR' not found in C:\xampp\htdocs\myocr\index.php:10 Stack trace: #0 {main} thrown in C:\xampp\htdocs\myocr\index.php on line 10
This is TesseractOCR.//echoed text from file that holds TesseractOCR class.
Inclusion path:
include ("C:/xampp/htdocs/myocr/vendor/thiagoalessio/tesseract_ocr/src/TesseractOCR.php");
If i use(which is suggested in repo readme, use thiagoalessio\TesseractOCR\TesseractOCR;, then it throws:
Fatal error: Uncaught Error: Class 'thiagoalessio\TesseractOCR\TesseractOCR' not found in C:\xampp\htdocs\myocr\index.php:10 Stack trace: #0 {main} thrown in C:\xampp\htdocs\myocr\index.php on line 10
My question is: How it hits test message, but won't hit TesseractOCR class?
EDIT5:
If i require_once "./vendor/autoload.php"; , it throws:
Fatal error: Uncaught thiagoalessio\TesseractOCR\TesseractNotFoundException: Error! The command "tesseract" was not found. Make sure you have Tesseract OCR installed on your system: https://github.com/tesseract-ocr/tesseract The current $PATH is C:\Program Files (x86)\NVIDIA Corporation\PhysX\Common;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;C:\WINDOWS\System32\OpenSSH\;C:\Program Files\Git\cmd;C:\Program Files\nodejs\;C:\xampp\php;C:\ProgramData\ComposerSetup\bin;C:\Users\Eddie\AppData\Local\Microsoft\WindowsApps;;C:\Users\Eddie\AppData\Local\Programs\Microsoft VS Code\bin;C:\Users\Eddie\AppData\Roaming\npm;C:\Users\Eddie\AppData\Roaming\Composer\vendor\bin;C:\Program Files\heroku\bin in C:\xampp\htdocs\myocr\vendor\thiagoalessio\tesseract_ocr\src\FriendlyErrors.php:48 Stack trace: #0 C:\xampp\htdocs\myocr\vendor\thiagoalessio\tesseract_ocr\src\TesseractOCR.php(26): thiagoalessio\TesseractOCR\FriendlyErrors::checkTesseractPresence('tesseract') #1 C:\xampp\ht in C:\xampp\htdocs\myocr\vendor\thiagoalessio\tesseract_ocr\src\FriendlyErrors.php on line 48
Btw, i added its patch to env variable:
I solved it!. My problem occurs that i didn't know about autoloaders in php.
Link that helped me is this.
My project structure is this:
Created project folder myocr.
After previous, downloaded latest stable version of Tesseract and installed it.
Depending on your system, you may be required to add value to your system env variable. You need to do that here
then
then
then
I'm assuming it self explanatory with images provided.
Next is getting TesseractOCR via composer:
composer require thiagoalessio/tesseract_ocr
Finally, before using code sample in repo, you need to call autoloader.
Index.php:
require_once('./vendor/autoload.php');//<-This!
use thiagoalessio\TesseractOCR\TesseractOCR;
$content = new TesseractOCR('text1.png');
$text = $content->run();
echo $text;
This worked for me. Crucial thing to look after is directory structure.
localhost > myocr > index.php with its code, and after using composer you'll get vendor dir. and it's content. Image path in new TesseractOCR('text1.png'); is directory where both index.php and image are located.

Imagick multiple pages PDF to JPG fatal error

What does not work:
Converting filename-multiple-pages.pdf[0] PDF file to JPG
Converting filename-multiple-pages.pdf PDF file to JPG
Fatal error: Uncaught exception 'ImagickException' with message
'Postscript delegate failed `/path/to/filename-multiple-pages.pdf': No
such file or directory # error/pdf.c/ReadPDFImage/664' in ...
When I try this with a sollution found on the webs with fopen and then using readImageFile of the fopen handle:
Fatal error: Uncaught exception 'ImagickException' with message
'Postscript delegate failed `/tmp/magick-rGGsdy9f': No such file or
directory # error/pdf.c/ReadPDFImage/664'
What does work:
Converting filename-multiple-pages.pdf[1] PDF file to JPG (the second page)
Converting filename-single-page.pdf PDF to JPG [/list]
The used PHP codes:
<?php
// this does work for a single page file
// it does NOT work for multiple page file
// it does NOT work when using pdffile.pdf[0]
// it DOES work when using pdffile.pdf[1]
$filename = '/path/to/pdffile.pdf';
$im = new Imagick();
$im->readImage($filename);
$im = $im->mergeImageLayers(Imagick::LAYERMETHOD_FLATTEN);
$im->scaleImage(150, 150, true);
$im->writeImage('/path/to/image/pdffile.jpg');
?>
<?php
// i used alternative code which gave me the second /tmp/ dir error (see above)
$filename = '/path/to/pdffile.pdf';
$pdf_handle = fopen($filename, 'rb');
$doc_preview = new Imagick();
$doc_preview->setResolution(150,150);
$doc_preview->readImageFile($pdf_handle);
$doc_preview->setIteratorIndex(0);
$doc_preview->setImageFormat('jpeg');
$doc_preview->writeImage('/path/to/image/pdffile.jpg');
$doc_preview->clear();
$doc_preview->destroy();
?>
Installed modules by hosting provider
ImageMagick v6.7.2.7-5
Ghostscript 8.70
Does anyone have any idea what to do?
After some research I found out that the hosting provider didn't install recent versions. After a few days of testing and debugging they managed to install the latest versions and it all works now. The code in my post is good and can be used by others :).

Amazon Instant Accèss PHP SDK phar file

I am attempting to use https://github.com/amzn/amazon-instant-access-sdk-php for amazon instant access via php. I am not super familiar with phar files; but am starting to figure it out.
I included https://github.com/amzn/amazon-instant-access-sdk-php/blob/master/phar-stub.php in a file as shown below. (Modified a bit as I renamed phar file)
Phar::mapPhar('amazon-instant-access-sdk-php.phar');
require_once 'phar://amazon-instant-access-sdk-php.phar/vendor/symfony/class-loader/Symfony/Component/ClassLoader/UniversalClassLoader.php';
$classLoader = new Symfony\Component\ClassLoader\UniversalClassLoader();
$classLoader->registerNamespaces(array(
'Amazon' => 'phar://amazon-instant-access-sdk-php.phar/src',
'Psr' => 'phar://amazon-instant-access-sdk-php.phar/vendor/psr/log',
'Monolog' => 'phar://amazon-instant-access-sdk-php.phar/vendor/monolog/monolog/src'
));
$classLoader->register();
return $classLoader;
__HALT_COMPILER();
Then when I do in another file:
require_once('amazon-instant-access-phar-stub.php');
I get error:
Fatal error: Uncaught exception 'PharException' with message 'internal corruption of phar "/Applications/MAMP/htdocs/phppos/amazon-instant-access-phar-stub.php" (truncated manifest at stub end)' in /Applications/MAMP/htdocs/phppos/amazon-instant-access-phar-stub.php:17 Stack trace: #0 /Applications/MAMP/htdocs/phppos/amazon-instant-access-phar-stub.php(17): Phar::mapPhar('amazon-instant-...') #1 /Applications/MAMP/htdocs/phppos/amazon_link_account.php(3): require_once('/Applications/M...') #2 {main} thrown in /Applications/MAMP/htdocs/phppos/amazon-instant-access-phar-stub.php on line 17
I have tried re-downloading phar file and running different versions of php (5.3, 5.6)
I am not sure what is causing this error.
You could directly download the .phar file from the release.
If you have the .phar file, you don't need the source code from github. The source code on github is used to compile the .phar file.
In your php code, you could do something like this:
<?php
//import the phar file directly like you did
require_once('amazon-instant-access-sdk-php.phar’);
//before you initiate the class, you need to use the right name space:
use Amazon\InstantAccess\Signature as signature;
$credentialStore = new signature\CredentialStore();
?>
This one will work.
If you want to check exactly what's in the .phar file, you could extract it:
php -r '$phar = new Phar("amazon-instant-access-sdk-php.phar"); $phar->extractTo("/tmp/phar/");'
then you could browse the /tmp/phar/ for all the files in the .phar.

error in PHPExcel

I am new to php. and I want to write some data to an excel file using php. I want to use PHPExcel for this purpose but I dont know how to do it I have downloaded and copes the to folders Clases and Expamles to my project folder then I tried require_once "Classes/PHPExcel/IOFactory.php" $objTpl = PHPExcel_IOFactory::load("template.xlsx"); just these two lines but its showing an error canoy open the file then I created an excel file at the location C:\wamp\www\scrapproj\Classes\PHPExcel\Reader again it shows an error at another line. The error showing is Fatal error: Uncaught exception 'PHPExcel_Reader_Exception' with message 'Could not open tempplate.xlsx for reading! File does not exist.' in C:\wamp\www\scrapproj\Classes\PHPExcel\Reader\Excel2007.php on line 82 Please somebody hep me to solve this.
updated Now I have updated my code like the following $objTpl = PHPExcel_IOFactory::load("template1.xlsx");
$objTpl->setActiveSheetIndex(0);
$objTpl->getActiveSheet()->setCellValue('A2', 'PHPExcel');
// $filename=mt_rand(1,100000).'.xlsx';
$objWriter = PHPExcel_IOFactory::createWriter($objTpl, 'Excel5');
if(is_readable('template1.xlsx'))
{
$objWriter->save('template1.xlsx');
} Now its its running without any error. But after running the page I cant open the excel file directly its showing the error Excel canot open the file template1.xlsx because the file format or its extension is not valid please help me to solve it
You are looking for the file in the current working directory, you can use the getcwd command to see what your working directory is.
1)
echo getcwd() . "\n";
http://www.php.net/manual/de/function.getcwd.php
Furthermore check if you have permission on that file.
2)
is_readable($filename)
http://www.php.net/manual/en/function.is-readable.php
Answer to your updated question (in future, please close answered questions and ask a new question)
You're using the Excel5 Writer
$objWriter = PHPExcel_IOFactory::createWriter($objTpl, 'Excel5');
Which is used for writing BIFF format files, which should have the extension .xls
But you're saving the file with a .xlsx extension
$objWriter->save('template1.xlsx');
which is for OfficeOpenXML format files
BIFF files are created using the Excel5 Writer, and have an extension of .xls
OfficeOpenXML files are created using the Excel2007 Writer, and have an extension of .xlsx
Don't mix and match, writers and extensions aren't interchangeable

thumbs.db messing up my upload routine

I'm getting the following error while uploading a zip archive.
Warning: ZipArchive::extractTo(C:\xampplite\htdocs\testsite/wp-content/themes/mytheme//styles\mytheme/Thumbs.db) [ziparchive.extractto]: failed to open stream: Permission denied in C:\xampplite\htdocs\testsite\wp-content\themes\mythem\uploader.php on line 17
The thing I can't quite figure is that I don't see a thumbs.db file in either the zip archive or the destination folder that was created (the upload still processes, I just get these errors).
The function is below, line 17 is commented...
function openZip($file_to_open) {
global $target;
$zip = new ZipArchive();
$x = $zip->open($file_to_open);
if($x === true) {
$zip->extractTo($target); //this is line 17
$zip->close();
unlink($file_to_open);
} else {
die("There was a problem. Please try again!");
}
}
Looks like just a warning. I would ignore it. I'm betting the error happens when it tried to overwrite the thumbs.db file in the extraction directory.
Alternatively, use getNameIndex to get a list of files, filter thumbs.db and use the second parameter of extractTo to filter the files.
http://www.php.net/manual/en/function.ziparchive-getnameindex.php
http://www.php.net/manual/en/function.ziparchive-extractto.php
This path is all messed up
C:\xampplite\htdocs\testsite/wp-content/themes/mytheme//styles\mytheme/Thumbs.db
I guess this might be windows issue.
can you add a line above line 17 saying
echo $file_to_open; exit;
and tell us what it says when you try to upload file?
Assuming that the mangled path works, then there is a thumbs.db in the destination directory (by default a hidden file), and/or your script does not have permission to write to that file/directory. Windows is very big on spitting out "permission denied" when a file is in use by another process, rather than saying "In use by process XXX".

Categories