how can I download multiple PDF files using php - php

so I am making a web site that allows user to read from a xlsx file sheet and download all the data each in a separate pdf here is the code
<?php
ini_set('error_reporting', E_ALL);
ini_set('display_errors', true);
// Load Composer's autoloader
require 'vendor/autoload.php';
$file_name="";
//index.php
$message = '';
require_once __DIR__.'/../src/SimpleXLSX.php';
echo '<h1>XLSX to HTML</h1>';
if (isset($_FILES['file'])) {
if ( $xlsx = SimpleXLSX::parse( $_FILES['file']['tmp_name'] ) ) {
$filen=$_FILES['file']['tmp_name'];
echo '<h2>'.$xlsx->sheetName($_POST['sh']-1).'</h2>';
echo '<table border=1>';
$dim = $xlsx->dimension();
$num_cols = $dim[0];
$num_rows = $dim[1];
foreach ( $xlsx->rows($_POST['sh']-1) as $k => $r ) {
// if ($k == 0) continue; // skip first row
echo '<tr>';
if ($k == 0) echo '<td>' .$r[ 0 ]. '</td>';
else
echo '<td>' .substr_replace($r[ 0 ],"",strripos($r[ 0 ]," ")). '</td>';
echo '<td>' .$r[ 1 ]. '</td>';
echo '<td>' .$r[ 2 ]. '</td>';
echo '<td>' .$r[ 4 ]. '</td>';
echo'<td>' . $r[ 5 ]. '</td>';
echo'<td>' . $r[ 7 ]. '</td>';
echo'<td>' .$r[ 8 ] . '</td>';
echo '</tr>';
if ($k != 0) // skip first row
{$date = substr_replace($r[0], "", strripos($r[0], " "));
$factname = $r[1];
$name = $r[2];
$email = $r[4];
$phone = $r[5];
$post = $r[7];
$pack = $r[8];
echo $name;
if ($pack == '90') $garanti = '30 jours';
else if ($pack == '190') $garanti = '6 mois';
else if ($pack == '290') $garanti = '12 mois';
else if ($pack == '390') $garanti = '2 ans';
else if ($pack == '490') $garanti = '3 ans';
else if ($pack == '590') $garanti = '5 ans';
sendmail();
echo'<td>telecharger</td>';}
// echo "telecharger";
}
echo '</table>';
echo '</tr>';
}
echo '</table>';
}
else {
echo SimpleXLSX::parseError();
}
if(isset($_POST['charge'])) {
if (isset($_FILES['file'])) {
if ($xlsx = SimpleXLSX::parse($_FILES['file']['tmp_name'])) {
foreach ($xlsx->rows($_POST['sh']-1) as $k => $r) {
if ($k == 0) continue; // skip first row
$date = substr_replace($r[0], "", strripos($r[0], " "));
$factname = $r[1];
$name = $r[2];
$email = $r[4];
$phone = $r[5];
$post = $r[7];
$pack = $r[8];
if ($pack == '90') $garanti = '30 jours';
else if ($pack == '190') $garanti = '6 mois';
else if ($pack == '290') $garanti = '12 mois';
else if ($pack == '390') $garanti = '2 ans';
else if ($pack == '490') $garanti = '3 ans';
else if ($pack == '590') $garanti = '5 ans';
sendmail();
echo "telecharger";
}
}
echo "telecharger";
}
}
echo '<h2>Upload form</h2>
<form method="post" enctype="multipart/form-data">
*.XLSX <input type="file" name="file" />
<input placeholder="sheet number" name="sh" type="number" required>
<input type="submit" value="Parse" />
</form>';
function sendmail()
{
global $name;
global $file_name;
$file_name="";
echo $file_name;
include('pdf.php');
$pdf = new Pdf();
$file_name = "ORDER-".$name . '.pdf';
$html_code = '<link rel="stylesheet" href="bootstrap.min.css">';
$html_code .= fetch_customer_data();
$pdf->load_html($html_code);
$pdf->render();
$file = $pdf->output();
file_put_contents($file_name, $file);
// $pdf->stream($file_name) ->
}
and this is the pdf.php file
<?php
//pdf.php
require_once 'dompdf/autoload.inc.php';
use Dompdf\Dompdf;
class Pdf extends Dompdf{
public function __construct(){
parent::__construct();
}
}
?>
I want to download all the pdfs at the same time but it only downloads the first one and shows me this error
( ! ) Fatal error: Cannot declare class Pdf, because the name is already in use in C:\wamp64\www\vucrm\xl\simplexlsx-master\examples\pdf.php on line 0
I tried to add exit() at the end of sendmail function but this only download the first and shows no other data or errors
can anyone help thanks in advance

You need to use require_once at the top of your script, don't use include inside the function.
// Require this at the top of your file
require_once('pdf.php');
The issue is each time you call the function, it includes the PDF class again and it can only be declared once.

Downloadable PDF files in html link!
To Download PDF from HTML link using PHP with the help of header() function in php.
The header() function is used to send a raw HTTP header.
Sometimes it wants the user to be prompted to save the data such as generated PDF.
Syntax:
http response headers to download any application
header("Content-Type: application/octet-stream");
http response headers to set composition and file to download
header('Content-Disposition: attachment; filename="downloaded.pdf"');
The length of the requested file need to download
header("Content-Length: " . filesize("download.pdf"));
Reads a file and writes it to the output buffer.
readfile('original.pdf');
PHP codes
$file = $_GET["file"] .".pdf";
// We will be outputting a PDF
header('Content-Type: application/pdf');
// It will be called downloaded.pdf
header('Content-Disposition: attachment; filename="gfgpdf.pdf"');
$imagpdf = file_put_contents($image, file_get_contents($file));
echo $imagepdf;
HTML codes
<!DOCTYPE html>
<html>
<head>
<title>Download PDF using PHP from HTML Link</title>
</head>
<body>
<center>
<h2 style="color:green;">Welcome To GFG</h2>
<p><b>Click below to download PDF</b>
</p>
Download PDF Now</center>
</body>
</html>
Note: Remember that HTTP header() must be called before any actual output is sent, either by normal HTML tags, blank lines in a file or from PHP.
Example 1: Save below HTML file as htmllinkpdf.html and save PHP file as downloadpdf.php
Above example to illustrate concept of downloading PDF file using HTML link.
Downloading file appears to be PDF format but without any content which shows error on opening in any application.
See more here
Here is another simple solution in for loop

Related

failed to clone a script to a new server

i was trying to copy this script from one of my servers to another one
both of them are ubuntu 18 with php 5.6 on them
but i keep getting internal server error without changing anything
<?php
if(!isset($_POST['importSubmit'])){
header("Location: index.php");
}
date_default_timezone_set('UTC');
header('Content-Type: text/html; charset=utf-8');
$x = fopen($_FILES['file']['tmp_name'], 'r');
require('XLSXReader.php');
$xlsx = new XLSXReader($_FILES['file']['tmp_name']);
$sheetNames = $xlsx->getSheetNames();
foreach($sheetNames as $sheetName) {
$sheet = $xlsx->getSheet($sheetName);
array2Table($sheet->getData());
function array2Table($data) {
foreach($data as $row) {
echo "<tr>";
foreach($row as $cell) {
echo "<td>" . escape($cell) . "</td>";
}
echo "</tr>";
}
}
function escape($string) {
return htmlspecialchars($string, ENT_QUOTES);
}
?>
From what I can tell, you are using: https://github.com/gneustaetter/XLSXReader and this library is not installed in your new server. Install it, and you should probably be good.

How to pass on a filename as a variable between PHP-files?

I have this file1.php:
<?php
// Start the session
session_start();
?>
<?php
$path_to_check = '';
$needle = $_POST['query'];
foreach(glob($path_to_check . '*.xml') as $filename)
{
foreach(file($filename) as $fli=>$fl)
{
if(strpos($fl, $needle)!==false)
{
echo $filename . ' on line ' . ($fli+1) . ': ' . $fl;
}
}
}
$_SESSION["hit"] = $fli;
header('Location: file2.php');
?>
It gets a searchword from a form and searchs for it among all XML-files in the current directory. The XML-files in this directory are only two; 1.xml and 2.xml.
Say I search for a word occuring in 2.xml, then I would like to save "2.xml" as the variable $_SESSION["hit"] and use it in file2.php:
<?php
// Start the session
session_start();
?>
<?php
echo $_SESSION["hit"];
// Load XML file
$xml = new DOMDocument;
$xml->load($_SESSION["hit"]);
// Load XSL file
$xsl = new DOMDocument;
$xsl->load('stylesheet.xsl');
// Configure the transformer
$proc = new XSLTProcessor;
// Attach the xsl rules
$proc->importStyleSheet($xsl);
echo $proc->transformToXML($xml);
?>
Unfortunately,
echo $_SESSION["hit"];
returns just "2" and not "2.xml", so then
$xml->load($_SESSION["hit"]);
will not load the XML-file 2.xml (since the variable just returns 2).
What am I doing wrong here?
Many thanks in advance:-)
/Paul
<?php
// Start the session
session_start();
?>
<?php
$path_to_check = '';
$needle = $_POST['query'];
foreach(glob($path_to_check . '*.xml') as $filename)
{
foreach(file($filename) as $fli=>$fl)
{
if(strpos($fl, $needle)!==false)
{
echo $filename . ' on line ' . ($fli+1) . ': ' . $fl;
$_SESSION["hit"] = $filename;
}
}
}
header('Location: file2.php');
?>
you need to save the file name in session variable not the line number

passing one variable from one page to another for pdf generation

I have a page that I have used to retrieve some excel data written in php... by using phpexcel... this part provides me company information
echo '<form action="final.php" method="post">';
echo "<table border='1'>";
for ($rowcount = $rowCompanyInfoStart; $rowcount <= $rowCompanyInfoEnd; $rowcount++)
{
//$data = $objWorksheet->rangeToArray('A1:' . $maxCell['column'] . $maxCell['row']);
$rangeCoordinates = $colCompanyInfoStart . $rowcount . ':' . $colCompanyInfoEnd . $rowcount;
$rowData = $sheet->rangeToArray($rangeCoordinates, NULL, TRUE, FALSE);
echo "<tr>";
$companyname=$worksheet->getCell($column.$row)->getValue();
// echo $companyname;
foreach($rowData[0] as $result)
{
echo "<td>".$result." </td>";
}
echo "</tr>";
}
echo "</table>";
echo "<br />";
echo '<input type="submit" name="sub" value="Convert into PDF" />';
// echo '<input type="text" name="resName" value="$result">';
function getdatan()
{
global $result; // declare as global
return $result;
}
echo '</form>';
this part is where I get company information... it looks like the table area shown down part...
I retrieve info and able to show as "$result" variable and with submit button named "convert it into pdf" I send it into other php page where I use TCPDF ....
Normally, this part of second page
$pdf->SetFont('times', 'BI', 12);
// add a page
$pdf->AddPage('L', 'A4');
if(isset($_POST['submit']))
{
$result = $_GET['resName'];
$pdf->Write(20, $result, '', 0, 'C', true, 0, false, false, 0);
}
// set some text to print
$txt = <<<EOD
TCPDF Example 003
Custom page header and footer are defined by extending the TCPDF class and overriding the Header() and Footer() methods.
EOD;
// print a block of text using Write()
// $pdf->Write(20, $resultt, '', 0, 'C', true, 0, false, false, 0);
// ---------------------------------------------------------
ob_end_clean();
//Close and output PDF document
$pdf->Output('example.pdf', 'I');
However, I am unable to print "$result" in the second page... can you help me about how to print this table on pdf...
PS: please clarify your help...
Try this
Change :
echo '<input type="submit" name="sub" value="Convert into PDF" />';
To:
echo '<input type="submit" name="resName" value="Convert into PDF" />';
EDIT
Put this at the begining of your second page:
var_dump($_POST);
just to check what you are receiving from the first page.
Also change :
$result = $_GET['resName'];
to this:
$result = $_POST['resName'];
ok since I was on my own... I found solution by myself ....
on the first page of PHP...
session_start();
//rest of your code and then...
if($_SERVER['REQUEST_METHOD'] == 'POST') {
echo '<form action="final.php" method="POST">';
$tablo="<br />";
$tablo = $tablo."<table border=\"1\" cellpadding=\"2\" cellspacing=\"2\" align='center'>";
for ($rowcount = $rowCompanyInfoStart; $rowcount <= $rowCompanyInfoEnd; $rowcount++)
{
//$data = $objWorksheet->rangeToArray('A1:' . $maxCell['column'] . $maxCell['row']);
$rangeCoordinates = $colCompanyInfoStart . $rowcount . ':' . $colCompanyInfoEnd . $rowcount;
$rowData = $sheet->rangeToArray($rangeCoordinates, NULL, TRUE, FALSE);
//fazla bosluk olursa bunları aç ya da hucre bos mu kontrol et (cellExists ile)
//rowData = array_map('array_filter', $rowData);
//$rowData = array_filter($rowData);
$tablo= $tablo."<tr >";
$companyname=$worksheet->getCell($column.$row)->getValue();
// echo $companyname;
foreach($rowData[0] as $result)
{
$tablo= $tablo. "<td>".$result. " </td>";
}
$tablo= $tablo. "</tr>";
}
$tablo= $tablo. "</table>";
echo $tablo;
echo "<br />";
if($_SERVER['REQUEST_METHOD'] != 'POST') {
echo "SESSION Not AVAIL. first run.";
}
else{
$_SESSION['varname'] = $tablo;
}
echo '<input type="submit" name="resName" value="Convert into PDF" />';
}
so here I used both "POST request" instead of just "POST". It sends "REQUEST" without any "POST DATA"... and then for sending the data I created a a variable called "$table" I put all my rows and cell info into that and created a session so that second PHP can retrieve it....
ON the second PHP page I answer "request" and open "session" just like that
session_start();
//rest of your code and then...
if($_SERVER['REQUEST_METHOD'] != 'POST') {
echo "SESSION Not AVAIL. first run.";
$tablo = $_SESSION['varname'];
echo "SESSION now set.";
}
else{
$tablo = $_SESSION['varname'];
//echo "SESSION SET, value: " .$_SESSION['varname']. " and ". $_SESSION['color'];
}
if (isset($_SESSION['varname'])){
$tablo = $_SESSION['varname'];
// print_r($_SESSION);
//echo "Session Set: <br/>" . $tablo;
}
else{
echo "Session not set. Tablo is empty";
// echo "Session Set: <br/>" . $tablo;
}
so that's it!

echo text of html file after submit a password

I have to do a php website for college.
I have to create a password and a submit button. After the I have posted the password I should get text from a html file. What is the best to achieve that?
I tried:
foreach($files as $file2) {
if($_POST['submitPassword']){
if($file2 === '.' OR $file2 === '..' OR $file2 === 'thumbs.db' OR !is_dir($folder.'/'.$file2)) {continue;}
if(file_exists($folder.'/'.$file2.'/doubleindemnity.gif') AND file_exists($folder.'/'.$file2.'/DOUBLEINDEMNITY.htm')) {
echo '<div class="Container">';
echo "<div class='image2'><img src='$folder/$file/doubleindemnity.gif'>";
$lines4 = file($folder.'/'.$file2.'/DOUBLEINDEMNITY.htm');
$count = count($lines4);
for($a = 0;$a < $count;$a++) {
echo substr($lines4[$a],strlen($folder),strpos($lines4[$a], '.')-strlen($folder));
}
echo "</div>";
}
echo "</div>";
}
}
?>
Help would be highly appreciated:)
Cheers:)
You can easily include the contents of an html file through include(). For example:
include($folder.'/'.$file2.'/DOUBLEINDEMNITY.htm');
It will call the entire file, and output it (since it's not a PHP file for execution)

Headers downloading actual page content, not the csv file I've constructed

My goal here is to have the browser download a csv file using headers to do it. For some reason yet to be determined, the browser seems to be downloading the HTML content of the current page (and not the contents of the array I've given it).
Here is the code I've been using:
$arr1 = array(array("1","2","3","4"),array("2","1","6","6"));
$tmp_handle = fopen('php://memory', 'r+');
fputcsv($tmp_handle, $arr1);
header("Content-type: text/csv");
header("Content-Disposition: attachment; filename=file.csv");
rewind($tmp_handle);
echo stream_get_contents($tmp_handle);
I've followed the instructions of many articles / SO questions I've read and I don't see what's wrong with this code.
I of course appreciate any help that I can get here!
Here is the complete code (upon request):
<?php
global $wpdb;
// Get total number of active referrers
$referrer_check = $wpdb->get_results("SELECT * FROM ".$wpdb->prefix."referrer");
$num_of_referrers = 0;
foreach ( $referrer_check as $check)
{
$num_of_referrers++;
}
// Get total number of referral transactions
$num_of_referrals = 0;
$num_referral_check = $wpdb->get_results("SELECT * FROM ".$wpdb->prefix."referrer_transactions");
foreach ( $num_referral_check as $check)
{
$num_of_referrals++;
}
// Check for the top referrer
$top_referrer = $wpdb->get_row("SELECT referrer_id, count(*) as row_count FROM ".$wpdb->prefix."referrer_transactions GROUP BY referrer_id ORDER BY COUNT(*) DESC");
$top_referrer_result = $wpdb->get_row("SELECT * FROM ".$wpdb->prefix."referrer WHERE referrer_id = $top_referrer->referrer_id");
// Construct the table
// Create array for second table
$ref_transactions_table_arr = array(
array("Referee Name", "Referee ID", "Referee Sign Up", "Referee Email","Referrer ID","Referrer Name"));
foreach ($num_referral_check as $check)
{
$ref_transactions_table_arr[] = array(
$wpdb->get_var("SELECT billing_name FROM ".$wpdb->prefix."pmpro_membership_orders WHERE user_id = $check->buyer_id"),
$check->buyer_id,
$wpdb->get_var("SELECT user_registered FROM ".$wpdb->prefix."users WHERE ID = $check->buyer_id"),
$wpdb->get_var("SELECT user_email FROM ".$wpdb->prefix."users WHERE ID = $check->buyer_id"),
$wpdb->get_var("SELECT referrer_id FROM ".$wpdb->prefix."referrer WHERE referrer_id = $check->referrer_id"),
$wpdb->get_var("SELECT referrer_name FROM ".$wpdb->prefix."referrer WHERE referrer_id = $check->referrer_id")
);
}
// Create array for first table
$active_ref_table_arr = array(
array('Referrer Name', 'Referrer ID', '# of Referrals', 'Address','Referrer Email','Lifetime Referrals'));
foreach ( $referrer_check as $check)
{
$active_ref_table_arr[] = array(
$check->referrer_name,
$check->referrer_id,
$wpdb->get_var("SELECT count(*) FROM ".$wpdb->prefix."referrer_transactions WHERE referrer_id = $check->referrer_id"),
$check->referrer_street . " " . $check->referrer_city . ", " . $check->referrer_state . " " . $check->referrer_zip,
$wpdb->get_var("SELECT user_email FROM ".$wpdb->prefix."users WHERE ID= $check->referrer_id"),
$wpdb->get_var("SELECT count(*) FROM ".$wpdb->prefix."referrer_transactions WHERE referrer_id = $check->referrer_id")
);
}
// Download file
if(isset($_POST['export_tbl_one']))
{
$csvData = array(
array("1","2","3","4"),
array("2","1","6","6")
);
$fp = fopen('php://memory', 'w+');
/*foreach ($csvData as $row) {
fputcsv($fp, $row);
}*/
fputcsv($fp,$csvData);
rewind($fp);
$csvFile = stream_get_contents($fp);
fclose($fp);
header('Content-Type: text/csv');
header('Content-Length: '.strlen($csvFile));
header('Content-Disposition: attachment; filename="file.csv"');
exit($csvFile);
}
?>
<div class="nav">
<ul>
<li class="first">Total Referrers: <? echo $num_of_referrers; ?></li>
<li>Total Referals: <? echo $num_of_referrals; ?></li>
<li>Top Referrer: <? echo $top_referrer->referrer_id . ", " . $top_referrer_result->referrer_name . "(" . $top_referrer->row_count . ")"; ?></li>
<li>
<form method="POST" action="http://keepmecertified.com/acp">
<input type="submit" value="click me" name="export_tbl_one"/>
</form>
</li>
</ul>
</div>
<br>
<table class="table">
<caption>Referrer Transactions</caption>
<?
$num = 0;
foreach($ref_transactions_table_arr as $fields)
{
echo "<tr>";
foreach($fields as $data)
{
if($num == 0)
{
echo "<th class=\"ref_head\">$data</th>";
}
else
{
echo "<td>$data</td>";
}
}
echo "</tr>";
if($num == 0)
{
$num++;
}
}
?>
</table>
<table class="table">
<caption>Active Referrers</caption>
<?
$num = 0;
foreach($active_ref_table_arr as $fields)
{
echo "<tr>";
foreach($fields as $data)
{
if($num == 0)
{
echo "<th class=\"ref_head\">$data</th>";
}
else
{
echo "<td>$data</td>";
}
}
echo "</tr>";
if($num == 0)
{
$num++;
}
}
?>
</table>
Try this code:
$csvData = array(
array("1","2","3","4"),
array("2","1","6","6")
);
$fp = fopen('php://memory', 'w+');
foreach ($csvData as $row) {
fputcsv($fp, $row);
}
rewind($fp);
$csvFile = stream_get_contents($fp);
fclose($fp);
header('Content-Type: text/csv');
header('Content-Length: '.strlen($csvFile));
header('Content-Disposition: attachment; filename="file.csv"');
exit($csvFile);
I have looped the data to build the CSV as your code would not produce the result you expect. I have also retrieved the file as a string before outputting - this is just a nicety to add a Content-Length header. I have also - and this is the important bit - called exit to output the data, to prevent any more code being executed any prevent and HTML after this code being output.
If you are using this code and still having a problem, then the code is not being called - you should check any if statements etc that this code is wrapped in.
This is way late but let's hope this unblocks someone.
Use ob_end_clean() to clean out other buffers on the page.
Start with ob_end_clean(); and end with exit;
This way, only the output in between will be written to the file.

Categories