How do I save a PDF to my root file? DOMPDF - php

I am using a free extension of opencart which allows me to download invoice in PDF to my local system (Downloads folder).
I want two things to happen
I want to download PDF file in my root. (if I am working on localhost I want the file to download in root\abc\ )
The other thing i want is that there is an email textbox and email button what I want is that I want to send email to user(eAddress written in textbox) with auto attachment of that downloaded pdf file located in(root\abc)
CODE :
$pdf = (isset($this->request->get['pdf'])) ? true : false;
$eFlag= (isset($this->request->get['email'])) ? true : false;
if ($pdf){
$this->response->setOutput(pdf($this->render(),$this->data['orders']));
}
elseif ($eFlag) {
$fp = fopen(DIR_DOWNLOAD . "meeru.pdf","wb");
$dataHtml = $this->render();
$name = $this->data['orders'];
if (count($name) > 1) {
$name = "Orders";
}else{
$name = 'Order_'.$name[0]['order_id'];
}
$pdf = new DOMPDF;
$pdf->load_html($dataHtml );
$pdf->render();
fwrite($fp , $pdf->output( array("compress" => 0) ));
fclose($fp );
$this->response->setOutput("File Saved");
}
else{
$this->response->setOutput($this->render());
}
Its downloading just one time (for the first time in root/download)

Related

problem when compile .docx file from codeigniter php

i have this simple code that generate a new .docx file from a sample with some "token" to modify
this code work in a local MAMP webserver
$template_file_name = 'template2.docx';
$rand_no = rand(111111, 999999);
$fileName = "results_" . $rand_no . ".docx";
$folder = "results";
$full_path = $folder . '/' . $fileName;
echo $full_path;
try
{
if (!file_exists($folder))
{
mkdir($folder);
}
//Copy the Template file to the Result Directory
copy($template_file_name, $full_path);
// add calss Zip Archive
$zip_val = new ZipArchive;
//Docx file is nothing but a zip file. Open this Zip File
if($zip_val->open($full_path) == true)
{
// In the Open XML Wordprocessing format content is stored.
// In the document.xml file located in the word directory.
$key_file_name = 'word/document.xml';
$message = $zip_val->getFromName($key_file_name);
$timestamp = date('d-M-Y H:i:s');
// this data Replace the placeholders with actual values
$message = str_replace("token1", "text to replace", $message);
//Replace the content with the new content created above.
$zip_val->addFromString($key_file_name, $message);
$zip_val->close();
}
echo "<script type='text/javascript'>alert('file creato');</script>";
}
catch (Exception $exc)
{
$error_message = "Error creating the Word Document";
var_dump($exc);
}
in online webserver despite the file and folder are 777 privileges ,the file was created but without my text to replace
in codeigniter i get this error:
$message = $zip_val->getFromName($key_file_name);
$zip_val->addFromString($key_file_name, $message);
$zip_val->close();
anyone can help me ?
the stranger thigs are that in webserver in local work without problem, on webserver online doesnt work
i hope in your answer
thanks a lot

create clickable link in php

I am working with wordpress -> contact form 7 and saving the data with contact form 7 to database extension plugin.
The plugin has filters to modify data before saving into database. ([Like This Page])1
now i wanted to save the file into different folder on the server and output link to that file into the admin panel. i used the filter like this.
function cfdbFilterSaveFile($formData) {
// CHANGE THIS: CF7 form name you want to manipulate
$formName = 'DemoReport';
// CHANGE THIS: upload field name on your form
$fieldName = 'Report';
// CHANGE THIS: directory where the file will be saved permanently
$uploaddir = '/home2/username/public_html/example.com/report/wp-content/uploads/reports/';
$urlDir = 'http://example.com/report/wp-content/uploads/reports/';
if ($formData && $formName == $formData->title && isset($formData->uploaded_files[$fieldName])) {
// make a copy of data from cf7
$formCopy = clone $formData;
// breakdown parts of uploaded file, to get basename
$path = pathinfo($formCopy->uploaded_files[$fieldName]);
// directory of the new file
$newfile = $uploaddir . $path['basename'];
// check if a file with the same name exists in the directory
if (file_exists($newfile)) {
$dupname = true;
$i = 2;
while ($dupname) {
$newpath = pathinfo($newfile);
$newfile = $uploaddir . $newpath['filename'] . '-' . $i . '.' . $newpath['extension'];
if (file_exists($newfile)) {
$i++;
} else {
$dupname = false;
}
}
}
// make a copy of file to new directory
copy($formCopy->uploaded_files[$fieldName], $newfile);
// save the path to the copied file to the cfdb database
$formCopy->posted_data[$fieldName] = $newfile;
$path = pathinfo($newfile);
$filelink = '<a href=' . $urlDir . $path['basename'] . '>' . $path['basename'] . '</a>';
$formCopy->posted_data[$fieldName . '-url'] = $filelink;
// delete the original file from $formCopy
unset($formCopy->uploaded_files[$fieldName]);
return $formCopy;
}
return $formData; }
add_filter('cfdb_form_data', 'cfdbFilterSaveFile');
Now with this code the file is saved into the folder on the server as expected but i am not able to output the clickable link to the saved file in the admin panel tables. In place of clickable links the full url is there. As in the screenshot.
ScreenShot
The output is coming as full URL (as marked 1 in screenshot), while i want the url to output as a link to the file (something like 2 in screenshot). I tried to use echo() and sprintf but got php syntex error.
Thanks for the suggestions. I have found alternate way to output links. What I have to do is output the form submission data on a webpage and convert links clickable by javascript as suggested by #Ovidash ... That is a acceptable workaround for my issue. Thanks for all the suggestions.

How to download a specific file(csv) using a php script

im generating a daily report from a php script, it is residing in a folder as follows
report_2015_02_15.csv
report_2015_02_16.csv
report_2015_02_17.csv
report_2015_02_18.csv
report_2015_02_19.csv
And im sending my users an email with link to download, once they click the download link the download script triggers and prepares the download. It currently gets all the files into an array sorts it and finds the latest for the download,
this method has a flow in it where, even when you go to a email that is 2 weeks older and clicks the download link, it gives you the latest report instead of giving the two weeks older report.
so can anybody tell me a way to send the download link in my email with a relationship to its corresponding file?
email script
$down_link = Config_Reader::readProjectConfig('tad')->base_url.'CSVDownload.php;
$mail = new Zend_Mail ();
$sentFromEmail = $config->sentFromrec;
$tr = new Zend_Mail_Transport_Sendmail ( '-f' . $sentFromEmail );
Zend_Mail::setDefaultTransport ( $tr );
$mail->setReturnPath($sentFromEmail);
$mail->setFrom ( $sentFromEmail, 'Reporting' );
$email_body = "Hi,<br /><br />Download the weekly details of adtracker projects, by clicking the link below.
<br /> Report<br /><br />Thank You.";
$mail->setBodyHtml ( $email_body );
$mail->addTo ( $weeklyReportRec);
$mail->setSubject ( "Report" );
try {
$mail->send ();
} catch ( Exception $e ) {
echo "Mail sending failed.\n";
}
download script
$basePath = "$download/dailyReport/";
$csvFiles = glob($basePath."/*.csv");
if(count($csvFiles)){
array_multisort($csvFiles, SORT_DESC);
$csvFile = $csvFiles[0];
}else{
exit("Server error!");
}
$h = fopen($csvFile, "r");
$contents = fread($h, filesize($csvFile));
You can use a query parameter indicating the report date on the download link. .../CSCDownload.php?date=2015/02/17
This will allow you to select the respective report from the available list.
You can use somthing like that as download script. I made just minum changes to get it work:
$date = $_GET['date'];
$basePath = "$download/dailyReport/";
$csvFiles = glob($basePath."/*.csv");
$file = $basePath . 'report_' . $date . '.csv';
$found = false;
foreach($csvFiles as $csvFile){
if($file === $csvFile){
$found = $csvFile;
// You have found the file, so you can stop searching
break;
}
}
if(false === $found){
exit("Server error!");
}
$h = fopen($found, "r");
$contents = fread($h, filesize($found));
Now you can call you script in your browser with "example.com/getcsvfile.php?date=2015_02_15" without worrying about injection, because you check if the file is one of the csv files.

Secureimage in CodeIgniter

So I wan't to use secureimage on CI coz' I don't want to use the default CAPTCHA helper since it doesn't have an audio option but I have a problem displaying the audio when using secureimage.
I copied the whole secureimage folder that I downloaded from the site to the library of CI.
Displaying the image is fine and also checking the inputted code. But my problem is displaying the audio file. I have no idea how to do it.
Here is how I displayed the image and for checking (already used the secureimage library):
function captcha_image(){
$img = new Securimage();
return $img->show();
}
public function captcha_check(){
$img = new Securimage();
$input = $this->input->post('imagecode');
$result = $img->check($input);
if($result)
$message = "success";
else
$message = "try again";
}
My view:
<img src="<?php echo site_url('form/captcha_image') ?>" alt='captcha' />
If you are using this library
https://github.com/subdesign/CI-HTI-Securimage
So The Method to get the Audio file is
$img->outputAudioFile();
But you have to configure ( settings ) the audio path directory and make sure its rewritable
$settings['audio_path'] = '....';// If you didn't configure this it will secureimage library path and follow by dir /audio/
$settings['audio_noise_path'] = '...';//save as above audio path
$settings['audio_use_noise'] = true; // true or false;
$settings['degrade_audio'] = true; // true or false;
// Then init the secureimage with the options
$img = new Securimage($settings);
$img->show(); // this will show the image src
$img->outputAudioFile(); // this will output the audio file to the browser

PHP dynamic zip file creation crashes with non-image filetypes. (wp)

I have a function that takes uploaded files (WORDPRESS) and adds them to a (newly created) zip file.
every new file is added to the zip (if is not yet created - the first file will create one ) and also to a comment with the list of the files.
function Ob99_generate_zip_file($meta) {
// we always need post_id , right ?
if( isset($_GET['post_id']) ) {
$post_id = $_GET['post_id'];
} elseif( isset($_POST['post_id']) ) {
$post_id = $_POST['post_id'];
}
//setting some more variables.
$file = wp_upload_dir();// take array
$file2 = wp_upload_dir();//debug
$zipname = $file['path'].'file.zip'; // set zip file name
$file = trailingslashit($file['basedir']).$meta['file'];// construct real path
// Without this next condition the function dies. WHY ??
list($orig_w, $orig_h, $orig_type) = #getimagesize($file); // not help to comment
if (!$orig_type == IMAGETYPE_GIF || !$orig_type == IMAGETYPE_PNG|| !$orig_type == IMAGETYPE_JPEG) {
//why other filetypes not working ??
return ;
}
$zip = new ZipArchive; // initiatte class
$zip->open($zipname , ZipArchive::CREATE); // open buffer
$new_filename = substr($file,strrpos($file,'/') + 1); //we do not need nested folders
$zip->addFile($file,$sitename.'/'.$new_filename); // we add the file to the zip
if (file_exists($zipname)){
$comment = $zip->getArchiveComment(); // if the file already exist read the comment
}
else { // if not - let´s give it a cool retro header
$comment_head = '*********************************'. PHP_EOL ;
$comment_head .= '****** <<< FILE CONTENT >>> *****'. PHP_EOL ;
$comment_head .= '*********************************'. PHP_EOL ;
}
$comment = $comment_head . $comment ;// add header before comment
$comment = $comment . PHP_EOL . PHP_EOL . $meta['file'] ; // add new file name
$zip->setArchiveComment($comment); // and comment
$zip->addFromString('filelist.txt', $comment); // create txt file with the same list
$zip->close()or die('can not create zip file'.$file.print_r($meta).'---- DEBUG SEPERATOR ---- '.print_r($file2)); // FINISHED or DIE with debug
}
My problem : if I try to upload any file other than an image - the function will DIE .
I have added a condition for checking imagetype - but I would like to know why it is crashing and how to make it work without said condition ...
Does the zip function have any problems with PDF , doc or anyother ? is that a wordpress problem ?
The problem section seems to be where you're asking PDFs, etc. their image size. Why don't you try:
$image_size = getimagesize($file);
if($image_size===false)
{
// This is not an image
// Do what you want to PDFs, etc.
}
else
{
// This is an image
// Find out image type, dimensions, etc.
}

Categories