How to use variables outside the loop in FPDF - php

I am generating a PDf doc using FPDF, when I click send button on a row in a table, I wanted to Generate a PDF for that Record and send it to the record email.
The PDF gets Generated normally, but I want to use a Variable "email" of each record to send to that record .. but On $to, I couldn't use email variable from my database.
I tried all combination of things and I am missing something for sure. The $idx is an Id from previous page (Index.php) posting data to "mail.php) where my PDF gets generated.
<!-- Index.php -->
<a class = "btn btn-info pid"
href = "mailto.php?idx=<?php echo $f_staff['id']?>" data-toggle="tooltip" title="Email This">
<span class="glyphicon glyphicon-envelope"></span>
</a>
<!-- mailto.php -->
<?php
require('../fpdf/fpdf.php');
$db = new PDO('mysql:host=localhost;dbname=mcle','root','PASS');
// CREATE AND SAVE THE PDF DOCUMENT
class pdf extends FPDF
{
function header()
{
Bla Bla Bla Bla.!
}
function viewTable($db)
{
$this->SetFont('Times','',12);
$idx = $_GET['idx'];
$stmt = $db->query("SELECT
staff.id,
staff.fname,
staff.lname,
staff.staff_bar_no,
staff.email
FROM staff JOIN attendance ON staff.staff_bar_no = attendance.staff_bar_no
WHERE attendance.event_id = 13 AND staff.id = '$idx'");
while($data = $stmt->fetch(PDO::FETCH_OBJ))
{
(This part WORKS fine with $data->Somevariables...
$this->Cell(80,6,$data->fname." ".$data->lname ,0,0,'L');
Bla Bla Bla Bla.!
}
}
}
$pdf = new pdf();
$pdf->AddPage('P','A4',0);
$pdf->view_pre_Table($db);
$pdf->viewTable($db);
// email stuff (change data below)
This is where I wanted to use Email Variable from the Array above... Tried $data->email; didn't work
$to = "email#email.net";
Bla Bla Bla Bla.!
// send message
mail($to, $subject, $body, $headers);
?>
Variables outside the while loop are consifered unidentified!

I’m not save in php, something like this could work:
<!-- mailto.php -->
<?php
require('../fpdf/fpdf.php');
$db = new PDO('mysql:host=localhost;dbname=mcle','root','PASS');
// CREATE AND SAVE THE PDF DOCUMENT
class pdf extends FPDF
{
//declare empty array
public $datas = [];
function header()
{
Bla Bla Bla Bla.!
}
function viewTable($db)
{
$this->SetFont('Times','',12);
$idx = $_GET['idx'];
$stmt = $db->query("SELECT
staff.id,
staff.fname,
staff.lname,
staff.staff_bar_no,
staff.email
FROM staff JOIN attendance ON staff.staff_bar_no = attendance.staff_bar_no
WHERE attendance.event_id = 13 AND staff.id = '$idx'");
while($data = $stmt->fetch(PDO::FETCH_OBJ))
{
array_push(this->datas,$data); //push each data into array
(This part WORKS fine with $data->Somevariables...
$this->Cell(80,6,$data->fname." ".$data->lname ,0,0,'L');
Bla Bla Bla Bla.!
}
}
}
$pdf = new pdf();
$pdf->AddPage('P','A4',0);
$pdf->view_pre_Table($db);
$pdf->viewTable($db);
// email stuff (change data below)
// now you can iterate over $pdf->datas
// send message
mail($to, $subject, $body, $headers);
?>

Here is my code:
$pdf = new pdf();
$pdf->AddPage('P','A4',0);
$pdf->view_pre_Table($db);
$pdf->viewTable($db);
//$pdf->Output(); //This is if you want an Output to the screen Rather than emailing..
$emailto = $_GET['idx'];// changed this it was base in id, changed to email instead and
assigned it to $emailto, then used it to get mail recipients.
// email stuff (change data below)
$to = $emailto;
$from = "LSNC MCLE";
$subject = "Your LSNC MCLE Attendance Certificate";
$message = "<p>Please see the attachment.</p>";

I did manage to make it work:
$pdf = new pdf();
$pdf->AddPage('P','A4',0);
$pdf->view_pre_Table($db);
$pdf->viewTable($db);
//$pdf->Output();
$emailto = $_GET['idx']; // email stuff (change data below)
$to = $emailto;
$from = "LSNC MCLE";
$subject = "Your LSNC MCLE Attendance Certificate";
$message = "<p>Please see the attachment.</p>";

Related

Moodle email templates

I am working on a Learning Management System build upon Moodle. I want to add an email header and footer for each email.
I did some change in Moodle for adding an image in ./lib/moodlelib.php as follows:
function email_to_user($user, $from, $subject, $messagetext, $messagehtml = '', $attachment = '', $attachname = '',
$usetrueaddress = true, $replyto = '', $replytoname = '', $wordwrapwidth = 79) {
global $CFG, $PAGE, $SITE;
// Append image at top
if($messagehtml){
$tmp = $messagehtml;
// Added image here
$messagehtml = '<img src="'.$CFG->wwwroot.'/images/logo.png" alt="LMS" /><br/>';
// $messagehtml = $image;
$messagehtml .= $tmp;
}
if($messagetext){
$tmp = $messagetext;
// Added image here
$messagetext = '<img src="'.$CFG->wwwroot.'/images/logo.png" alt="LMS" /><br/>';
// $messagehtml = $image;
$messagetext .= $tmp;
}
....................
but I want the header and footer as fixed templates. Please help me.
You could create a message header in a language file (in English either directly under /lang/en or in a plugin) and then add the following string in the language file:
$string ['message_header'] = '<p> write here whatever your style and HTML structure you want in your header</p>
adding your image as well <img src="'.$CFG->wwwroot.'/images/logo.png" alt="LMS" />';
Then you could write a string for your footer as well:
$string ['message_footer'] = 'Your HTML footer here';
And finally you could insert your strings in the message:
$message = 'here your body';
// insert message header - if your language string is in /lang/moodle.php:
$message = get_string ( 'message_header') . $message;
// insert message footer - if your language string is in your /local/myplugin:
$message .= get_string ( 'message_footer', 'local_my_plugin' );
This way your header and footer may be customized at will if you change them directly in the language file (or, in the DB. See here).
a little bit too late, but i hope it helps others:
https://docs.moodle.org/dev/Themed_emails just look for e-mail templates in /var/www/html/moodle/lib/templates. The template with a name email_html.mustache should be the right one.

HTML site with AJAX request image onclick execute PHP file

I will really appreciate if you could help me in that coding. I really need help.
I want with single press over the image, to get the data from fields sent over email.
So my HTML image code like that :
<img src="images/some.png" id="help" onClick="help();">
Right before that tag in HTML file I put AJAX like that:
<script type="text/javascript">
function help() {
$.get("/help.php");
return false;
}
</script>
And with that function i want, when the user click over the image to execute my PHP script which is on other file and it contains code like that :
help.php
<?php
{
$helpSubject = 'help';
$webMaster = '****#mail.com';
$helpField = $_POST['help'];
$problemField = $_POST['problem'];
$body = <<<EOD
<br><hr><br>
Help: $help <br>
Problem: $problem <br>
EOD;
$headers = "Reason: $help\r\n";
$headers = "Content-type: text/html\r\n";
$success = mail($webMaster, $helpSubject, $body, $headers);
$theResults = <<<EOD
Success
EOD;
echo "$theResults";
}
?>
Something is wrong, and I can't find what. Could anyone help me with that?
Thank you.

phpmailer auto include local images

I'm currently busy with phpmailer and wondered how to automatically embed local images in my email using a script. My idea was to upload a html file and a folder containing images and let a script replace the <img src tags to the cid ones.
Now what I got so far is:
$mail = new PHPMailer(true);
$mail->IsSendmail();
$mail->IsHTML(true);
try
{
$mail->SetFrom($from);
$mail->AddAddress($to);
$mail->Subject = $subject;
$mail->Body = embed_images($message, $mail);
$mail->Send();
}
Now I've got this incomplete function that scans the html body and replace the src tags:
function embed_images(&$body, $mailer)
{
// get all img tags
preg_match_all('/<img.*?>/', $body, $matches);
if (!isset($matches[0])) return;
$i = 1;
foreach ($matches[0] as $img)
{
// make cid
$id = 'img'.($i++);
// now ?????
}
$mailer->AddEmbeddedImage('i guess something with the src here');
$body = str_replace($img, '<img alt="" src="cid:'.$id.'" style="border: none;" />', $body);
}
I'm not sure what I should do here, do you retrieve the src and replace it with cid:$id ?
As they are local images i do not have the trouble of web src links or whatever...
You got the right approach
function embed_images(&$body,$mailer){
// get all img tags
preg_match_all('/<img[^>]*src="([^"]*)"/i', $body, $matches);
if (!isset($matches[0])) return;
foreach ($matches[0] as $index=>$img)
{
// make cid
$id = 'img'.$index;
$src = $matches[1][$index];
// now ?????
$mailer->AddEmbeddedImage($src,$id);
//this replace might be improved
//as it could potentially replace stuff you dont want to replace
$body = str_replace($src,'cid:'.$id, $body);
}
}
Why don't you embed the images directly in the HTML in base64?
You just have to convert your images in base64, and then include them like this:
<img src="data:image/jpg;base64,---base64_data---" />
<img src="data:image/png;base64,---base64_data---" />
I don't know if this is relevant in your case or not, but I hope it helps.
function embed_images(&$body, $mailer) {
// get all img tags
preg_match_all('/<img[^>]*src="([^"]*)"/i', $body, $matches);
if (!isset($matches[0]))
return;
foreach ($matches[0] as $index => $img) {
$src = $matches[1][$index];
if (preg_match("/\.jpg/", $src)) {
$dataType = "image/jpg";
} elseif (preg_match("/\.png/", $src)) {
$dataType = "image/jpg";
} elseif (preg_match("/\.gif/", $src)) {
$dataType = "image/gif";
} else {
// use the oldfashion way
$id = 'img' . $index;
$mailer->AddEmbeddedImage($src, $id);
$body = str_replace($src, 'cid:' . $id, $body);
}
if($dataType) {
$urlContent = file_get_contents($src);
$body = str_replace($src, 'data:'. $dataType .';base64,' . base64_encode($urlContent), $body);
}
}
}

Unset a php value on each run of for each

I am running the following script, which is phpmailer, at the end of each for each run I want it to clear the contents of $name , either that or $row->['leadname'] , I have tried using unset at the bottom of the script but this seems to have no effect and I am just getting from a list of 3 people 2 of them saying dear bob , and the other saying dear {name} , even though the contacts are called, bob, fred and wendy.
<?php
$formid = mysql_real_escape_string($_GET[token]);
$templatequery = mysql_query("SELECT * FROM hqfjt_chronoforms_data_addmailinglistmessage WHERE cf_id = '$formid'") or die(mysql_error());
$templateData = mysql_fetch_object($templatequery);
$gasoiluserTemplate = $templateData->gasoilusers;
$dervuserTemplate = $templateData->dervusers;
$kerouserTemplate = $templateData->kerousers;
$templateMessage = $templateData->mailinglistgroupmessage;
$templatename = $templateData->mailinglistgroupname;
?>
<?php
require_once('./send/class.phpmailer.php');
//include("class.smtp.php"); // optional, gets called from within class.phpmailer.php if not already loaded
$mail = new PHPMailer(true); //defaults to using php "mail()"; the true param means it will throw exceptions on errors, which we need to catch
// $body = file_get_contents('contents.html');
$body = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<style>#title {padding-left:120px;padding-top:10px;font-family:"Times New Roman", Times, serif; font-size:22px; font-weight:bold; color:#fff;}</style>
</head>
<body>
<div style="background:
none repeat scroll 0% 0% rgb(6, 38,
97); width:780px;">
<img id="_x0000_i1030" style="padding-left:100px;padding-right:100px;"
src="http://www.chandlersoil.com/images/newsletter/header.gif"
alt="Chandlers Oil and Gas"
border="0" height="112"
width="580">
<div id="title">{message}</div>
</div>
</body>
</html>
';
// $body = preg_replace('/\\\\/i', $body);
$mail->SetFrom('crea#cruiseit.co.uk', 'Chandlers Oil & Gas');
$mail->AddReplyTo('crea#cruiseit.co.uk', 'Chandlers Oil & Gas');
$mail->Subject = "Your Fuel Prices From Chandlers Oil & Gas";
$query = "SELECT leadname,businessname,email FROM hqfjt_chronoforms_data_addupdatelead WHERE keromailinglist='$kerouserTemplate' AND dervmailinglist='$dervuserTemplate' AND gasoilmailinglist='$gasoiluserTemplate'";
$result = mysql_query($query);
// Bail out on error
if (!$result)
{
trigger_error("Database error: ".mysql_error()." Query used was: ".htmlentities($query), E_USER_ERROR);
die();
}
while ($row = mysql_fetch_array ($result)) {
$mail->AltBody = "To view the message, please use an HTML compatible email viewer!";
// THIS PULLS THE CLIENTS FIRST NAME OUT ON EACH LOOP
$firstname = $row["leadname"];
//THIS PULLS THE CLIENTS BUSSINESS NAME OUT ON EACH LOOP
$businessname = $row["businessname"];
// IF THE FIRST NAME FIELD IS BLANK USE THE BUSINESS NAME INSTEAD
if ($firstname = '')
{$name = $row["businessname"];}
else
{$name = $row["leadname"];}
// THIS REPLACES THE {NAME} IN THE PULLED IN TEMPLATE MESSAGE WITH THE CLIENTS NAME DEFINED IN $name
$body = str_replace('{name}', $name, $body);
// THIS REPLACES {fuel} IN THE PULLED IN TEMPLATE WITH THE TEMPLATE NAME (WHICH IS THE TYPE OF FUEL)
$body = str_replace('{fuel}', $templatename, $body);
// THIS REPLACES THE {message} IN THE $body ARRAY WITH THE TEMPLATE MESSAGE HELD IN $templateMessage
$body = str_replace('{message}', $templateMessage, $body);
$mail->MsgHTML($body);
$mail->AddAddress($row["email"], $row["leadname"]);
if(!$mail->Send()) {
echo "Mailer Error (" . str_replace("#", "#", $row["email"]) . ') ' . $mail->ErrorInfo . '<br>';
} else {
echo "Message sent to :" . $row["full_name"] . ' (' . str_replace("#", "#", $row["email"]) . ')<br>';
}
// Clear all addresses and attachments for next loop
$mail->ClearAddresses();
$mail->ClearAttachments();
unset ($row['leadname']);
unset ($name;)
}
?>
It looks like you need to copy the contents of body into a new variable within your loop.
Currently you're overwriting the variable on the first run, removing the {name} placeholders.
// THIS REPLACES THE {NAME} IN THE PULLED IN TEMPLATE MESSAGE WITH THE CLIENTS NAME DEFINED IN $name
$newBody= str_replace('{name}', $name, $body);
// THIS REPLACES {fuel} IN THE PULLED IN TEMPLATE WITH THE TEMPLATE NAME (WHICH IS THE TYPE OF FUEL)
$newBody = str_replace('{fuel}', $templatename, $newBody);
// THIS REPLACES THE {message} IN THE $body ARRAY WITH THE TEMPLATE MESSAGE HELD IN $templateMessage
$newBody = str_replace('{message}', $templateMessage, $newBody);
$mail->MsgHTML($newBody);
$mail->AddAddress($row["email"], $row["leadname"]);
Also you can actually use arrays in str_replace, e.g.
$newBody = str_replace(array('{name}','{fuel}'),array($name,$fuel),$body);
the ; is in a wrong position.
Try
unset($name);
instead of
unset($name;),

Strange glitch with str_replace in my php script

I am having a strange problem with str_replace in my php code below. What is supposed to happen is on each loop it is supposed to replace {name} with the person's name pulled in from the database. What it is actually doing is if I mail two people, the first one it replaces with thier name, so they get an email dear, bob bla bla bla. The second one always seems to be dear , {name} bla bla bla. It is as though on the second loop, something is failing?
<?php
$formid = mysql_real_escape_string($_GET[token]);
$templatequery = mysql_query("SELECT * FROM hqfjt_chronoforms_data_addmailinglistmessage WHERE cf_id = '$formid'") or die(mysql_error());
$templateData = mysql_fetch_object($templatequery);
$gasoiluserTemplate = $templateData->gasoilusers;
$dervuserTemplate = $templateData->dervusers;
$kerouserTemplate = $templateData->kerousers;
$templateMessage = $templateData->mailinglistgroupmessage;
$templatename = $templateData->mailinglistgroupname;
?>
<?php
require_once('./send/class.phpmailer.php');
//include("class.smtp.php"); // optional, gets called from within class.phpmailer.php if not already loaded
$mail = new PHPMailer(true); //defaults to using php "mail()"; the true param means it will throw exceptions on errors, which we need to catch
// $body = file_get_contents('contents.html');
$body = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<style>#title {padding-left:120px;padding-top:10px;font-family:"Times New Roman", Times, serif; font-size:22px; font-weight:bold; color:#fff;}</style>
</head>
<body>
<div style="background:
none repeat scroll 0% 0% rgb(6, 38,
97); width:780px;">
<img id="_x0000_i1030" style="padding-left:100px;padding-right:100px;"
src="http://www.chandlersoil.com/images/newsletter/header.gif"
alt="Chandlers Oil and Gas"
border="0" height="112"
width="580">
<div id="title">{message}</div>
</div>
</body>
</html>
';
// $body = preg_replace('/\\\\/i', $body);
$mail->SetFrom('crea#cruiseit.co.uk', 'Chandlers Oil & Gas');
$mail->AddReplyTo('crea#cruiseit.co.uk', 'Chandlers Oil & Gas');
$mail->Subject = "Your Fuel Prices From Chandlers Oil & Gas";
$query = "SELECT leadname,businessname,email FROM hqfjt_chronoforms_data_addupdatelead WHERE keromailinglist='$kerouserTemplate' AND dervmailinglist='$dervuserTemplate' AND gasoilmailinglist='$gasoiluserTemplate'";
$result = mysql_query($query);
// Bail out on error
if (!$result)
{
trigger_error("Database error: ".mysql_error()." Query used was: ".htmlentities($query), E_USER_ERROR);
die();
}
while ($row = mysql_fetch_array ($result)) {
$mail->AltBody = "To view the message, please use an HTML compatible email viewer!";
// THIS PULLS THE CLIENTS FIRST NAME OUT ON EACH LOOP
$firstname = $row["leadname"];
//THIS PULLS THE CLIENTS BUSSINESS NAME OUT ON EACH LOOP
$businessname = $row["businessname"];
// IF THE FIRST NAME FIELD IS BLANK USE THE BUSINESS NAME INSTEAD
if ($firstname = '')
{$name = $row["businessname"];}
else
{$name = $row["leadname"];}
// THIS REPLACES THE {NAME} IN THE PULLED IN TEMPLATE MESSAGE WITH THE CLIENTS NAME DEFINED IN $name
$body = str_replace('{name}', $name, $body);
// THIS REPLACES {fuel} IN THE PULLED IN TEMPLATE WITH THE TEMPLATE NAME (WHICH IS THE TYPE OF FUEL)
$body = str_replace('{fuel}', $templatename, $body);
// THIS REPLACES THE {message} IN THE $body ARRAY WITH THE TEMPLATE MESSAGE HELD IN $templateMessage
$body = str_replace('{message}', $templateMessage, $body);
$mail->MsgHTML($body);
$mail->AddAddress($row["email"], $row["leadname"]);
if(!$mail->Send()) {
echo "Mailer Error (" . str_replace("#", "#", $row["email"]) . ') ' . $mail->ErrorInfo . '<br>';
} else {
echo "Message sent to :" . $row["full_name"] . ' (' . str_replace("#", "#", $row["email"]) . ')<br>';
}
// Clear all addresses and attachments for next loop
$mail->ClearAddresses();
$mail->ClearAttachments();
}
?>
$body contains the mail's template. In your loop, you assign the return value from str_replace() to this variable. After that, you cannot expect it to contain the original template upon a next iteration. You'll have to use a temporary variable for this:
while (...) {
$bodyTemp = str_replace('{name}', $name, $body);
$bodyTemp = str_replace('{fuel}', $templatename, $bodyTemp);
// ...
}
Also, to make your code a little more readable, might I suggest using strtr() instead:
while (...) {
$bodyTemp = strtr($body, array(
'{name}' => $name,
'{fuel}' => $templatename,
// ...
));
}
This saves you the repetitive invocations of str_replace().
Before the loop, $body may contain Dear {name}. Then you loop once, then it contains Dear Iain. Then in the second loop, there is no {name} to replace anymore.

Categories