Read an excel file stored in media folder - php

I'm developing a WordPress plugin that requires to upload an excel file and then read the data inside of it.
I'm using the function "media_handle_upload" to upload the excel file, then, when I try to use SpreadsheetReader to read the file there's an error saying that the file is not readable.
This is what I'm coding, (I know it's horrible coding, but I'm learning and this is just to get the plugin working)
if(isset($_FILES['test_upload_pdf'])){
$pdf = $_FILES['test_upload_pdf'];
// Use the wordpress function to upload
// test_upload_pdf corresponds to the position in the $_FILES array
// 0 means the content is not associated with any other posts
$uploaded=media_handle_upload('test_upload_pdf', 0);
// Error checking using WP functions
if(is_wp_error($uploaded)){
echo "Error uploading file: " . $uploaded->get_error_message();
}else{
echo $pdf."<br>";
$year = date('Y');
$month = date('m');
$targetPath = get_site_url()."/wp-content/uploads/".$year."/".$month."/".$_FILES['test_upload_pdf']['name'];
$targetPath2 = $_SERVER['DOCUMENT_ROOT']."/".$_SERVER["HTTP_HOST"]."/wp-content/uploads/".$year."/".$month."/".$_FILES['test_upload_pdf']['name'];
echo "<br>";
echo $targetPath2;
echo "<br>";
try
{
$Reader = new SpreadsheetReader($targetPath2);
}
catch (Exception $E)
{
echo $E -> getMessage();
}
I think the reader doesn't work because is trying to access "localhost" instead of the physical folder, for example, one of the $targetPath prints this:
http://127.0.0.1/wordpress/wp-content/uploads/2019/04/example.xlsx
So... My question is, there's a way to access the media files so I can open them with the reader?
Thanks.

Perhaps this helps:
https://developer.wordpress.org/reference/functions/wp_upload_dir/
Otherwise try to hardcode folder "/your/path/to/upload/folder/file.extension" and find out how to create this programmaticly

Related

phpSpreadSheet - how to save charts to separate .png files?

I'm using PHP spreadsheet class to successfully create an xlsx spreadsheet with several charts. The spreadsheet is written down to disk.
After that I would like to export these charts from spreadsheet to separate .png files. Based on documentation I tried to use the following code:
$inputFileType = \PhpOffice\PhpSpreadsheet\IOFactory::identify($XLSXfilepath);
$reader = IOFactory::createReader($inputFileType);
$reader->setIncludeCharts(true);
$spreadsheet = $reader->load($XLSXfilepath, $reader::LOAD_WITH_CHARTS);
$nr = 1;
foreach ($spreadsheet->getWorksheetIterator() as $worksheet) {
$chartNames = $worksheet->getChartNames();
foreach ($chartNames as $chartName) {
$chart = $worksheet->getChartByName($chartName);
try{
//the following code results false:
$res = $chart->render('temp/chart'.$nr.'.png');
} catch(Exception $e){
//this doesn't happen, which means then no exception is thrown:
print $e->getMessage();
}
$nr++;
}
}
The problem is that $chart->render results false with any error message and - of course - no .png file is saved on disk. But no exception is thrown.
I double-checked that I have full rights to save files to the selected location and of course, there is enough free space on disk...
I also checked that foreach loop properly finds all charts, which are saved in the .xlsx file.
Is there any way to find out why the charts are not rendered to files?

How to save file in subfolder using php

I have a script with a mysql query which saves a file called invoice.xml every day automatically by running a cron job. In case no data is found a no_orders.txt is saved.
I would like this file not be saved to the same folder as the script.php file is in but to a subfolder called invoices.
The renaming of the old invoice.xml is done with the following code
// rename old file
$nowshort = date("Y-m-d");
if(file_exists('invoice.xml')) {
rename('invoice.xml','invoice_'.$nowshort.'.xml');
}
The saving is done with the following code:
if($xml1 !='') {
$File = "invoice.xml";
$Handle = fopen($File, 'w');
fwrite($Handle, $xml1);
print "Data Written - ".$nowMysql;
fclose($Handle);
#print $xml;
die();
} else {
print "No new orders - ".$nowMysql;
$File = "no_orders_".$nowshort.".txt";
$Handle = fopen($File, 'w');
fclose($Handle);
die();
}
Could I please get assistance how to save this file to a subfolder. Also the renaming of the existing file would need to be within the subfolder then. I have already tried with possibilities like ../invoice/invoice.xml but unfortunately without any success.
Thank you
Just give the path of file 'invoice.xml' to $File.
Otherwise create some $Dir object which will point to Folder named 'invoice', then use accordingly
Use __DIR__ magic constant to retrieve your script.php directory, then you can append /invoice/invoice.xml .
Example if path to your script php something like this:
/var/www/path/to/script.php
$currentDir = __DIR__; //this wil return /var/www/path/to
$invoicePath = $currentDir.'/invoice/invoice.xml';

copy files from remote url of same extension different names

Hi I have successfully copied file from remote url to mine using copy
if(!#copy('http://www.example.com/download/somedoc.pdf','./pdf/somedoc.pdf'))
{
$errors= error_get_last();
echo "COPY ERROR: ".$errors['type'];
echo "<br />\n".$errors['message'];
} else {
echo "File copied from remote!";
}
But I need to do it manually and one at a time. I did Google for * file name with same extension like somedoc.pdf. anotherdoc.pdf, next.pdf.
Is'nt there anyway to copy automatically to my local server from remote url that is newly uploaded
Found My Ans:
yeah got it.. used simplehtmldom.. The html code or www.example.com was
<a target="_blank" style="text-decoration:none" href="./images/download/somedoc.pdf">somedoc and somename</a>
and my code was
include('../simple_html_dom.php');
// get DOM from URL or file
$html = file_get_html('http://www.example.com');
// find all link
foreach($html->find('a[target=_blank]') as $e)
echo $e->href . '<br>';
http://simplehtmldom.sourceforge.net/
now i will convert the output to variable and use the copy function
Thanks for the reponses guys..

replacing the process with file url instead of file upload in php

am uploading a Pdf file and passing it to getExtact function to extract pages from file which is being uploaded if any error in extraction we will send the file to decryptPDF function for which the input parameters are filename and filetempname for both the functions but here am using a file upload process i want to use file url like www.domainname.com/docs/1.pdf so that all the functions which are written already can be used : Below is my code
//here for the above variable values are coming from uploaded file here i want to use file url and all the pdf are in my own server
$FileName = $_FILES['inputfile']['name'];
$TempFileName = $_FILES['inputfile']['tmp_name']; $Folderpath='/home/domain/public_html/pdftest/temp';
try {
.
GetExtract($TempFileName,$FileName);
} catch (Exception $e) {
$responce = DecryptPDF($Folderpath,$Filename,$TempFileName);
if($responce == ''){
$Inputfile = $Folderpath.'/un_'.$Filename;
GetExtract($Inputfile,$FileName);
}else{
echo $responce;
}
As per my knowledge,local server $PATH is "/var/www/".Try putting your inputfiles in that location.Then only you can access the files using url.

Unable to create a folder in dropbox using Php API Dropbox using Wordpress

While User uploads the files, the folder should be automatically created in the dropbox with the username as folder name. and then after the files that were uploaded by the user should be saved in that folder.
Error thrown:
"
Error: Resource at uri: https://api.dropbox.com/1/metadata/dropbox/sweety could not be found."
The code is
// Upload
$wpschunks = explode("/",$wpsdbTmpFile);
for($i = 0; $i < count($wpschunks); $i++) {
$c = $i;
}
global $current_user;
$wpuserid = $current_user->data->ID;
$wpusername = $current_user->data->user_login;
$newfoldername = $wpusername;
// echo trim($wpsdb_path,'/').' //\\ ';
$folderMetadata = $dropbox->getMetaData(trim($wpsdb_path, '/') . '/' . $newfoldername, true);
if (!$folderMetadata['is_dir']) {
$dropbox->CreateFolder(trim($wpsdb_path, '/') . '/' . $newfoldername, "dropbox");
if ( !$dropbox->putFile(trim($wpsdb_path,'/').'/'.$newfoldername.'/'.$wpschunks[$c], $wpstmpFile,"dropbox") ) {
throw new Exception(__('ERROR! Upload Failed.','simpleDbUpload'));
}
if($wpsdb_delete_file == "True") {
if (isset($wpsdbTmpFile) && file_exists($wpsdbTmpFile)) {
unlink($wpsdbTmpFile);
}
}
}
Note:
When we create the blank folder manually in dropbox and then delete it and then if we try to upload the files the folder is create automatically(using this code) and the files also get uploaded.
I have no idea what "api version of 2010" means. :-) I don't know what library the Wordpress plugin is based on, but it looks like in this one, an error is raised when you request the metadata of a path that doesn't exist. I don't see why this is a problem... just handle the error and continue?
As an alternative, you could just not create the folder at all. Folders are implicitly created in Dropbox when you upload files into them. So you could just go straight to the $dropbox->putFile() call and skip checking for the folder and creating it if it doesn't already exist.

Categories