There seems to be a performance issue with the script as it is really slow. I was wondering what I could do to speed this up. If you have any ideas, please let me know. I can't seem to figure it out.
Below is the code:
<?php
include_once("connect.php.inc");
class HtmlEnc{
static function uniord($c) {
$ud = 0;
if (ord($c{0}) >= 0 && ord($c{0}) <= 127) $ud = ord($c{0});
if (ord($c{0}) >= 192 && ord($c{0}) <= 223) $ud = (ord($c{0})-192)*64 + (ord($c{1})-128);
if (ord($c{0}) >= 224 && ord($c{0}) <= 239) $ud = (ord($c{0})-224)*4096 + (ord($c{1})-128)*64 + (ord($c{2})-128);
if (ord($c{0}) >= 240 && ord($c{0}) <= 247) $ud = (ord($c{0})-240)*262144 + (ord($c{1})-128)*4096 + (ord($c{2})-128)*64 + (ord($c{3})-128);
if (ord($c{0}) >= 248 && ord($c{0}) <= 251) $ud = (ord($c{0})-248)*16777216 + (ord($c{1})-128)*262144 + (ord($c{2})-128)*4096 + (ord($c{3})-128)*64 + (ord($c{4})-128);
if (ord($c{0}) >= 252 && ord($c{0}) <= 253) $ud = (ord($c{0})-252)*1073741824 + (ord($c{1})-128)*16777216 + (ord($c{2})-128)*262144 + (ord($c{3})-128)*4096 + (ord($c{4})-128)*64 + (ord($c{5})-128);
if (ord($c{0}) >= 254 && ord($c{0}) <= 255) $ud = false; // error
return $ud;
}
static function toHtml($str){
$html_str = "";
while (strlen($str) > 0) {
preg_match("/^(.)(.*)$/u", $str, $match);
$test = utf8_decode($match[1]);
if ($test != "?") {
$html_str .= htmlentities(htmlentities($test));
} else if (strlen($match[1]) > 1) {
$html_str .= "&#".self::uniord($match[1]).";";
} else $html_str .= htmlentities(htmlentities($match[1]));
$str = $match[2];
}
return $html_str;
}
}
/*
List of mail servers
*/
function alreadyDone($domain){
$domain = strtolower($domain);
$qry = "SELECT * FROM emdb WHERE domain ='" . $domain . "'";
$result = mysql_query($qry);
return (mysql_num_rows($result)!=0);
}
$template_fn = $_REQUEST['template'];
//"mail_template.html";
$keywords = HtmlEnc::toHtml($_REQUEST['Keywords']);
$keywords = str_replace("&","&",$keywords);
$domain = $_REQUEST['Domain'];
$rank = $_REQUEST['Rank'];
$to = $_REQUEST['Email'];
$adminEmail = "test#example.com";
if (!alreadyDone($domain)) {
if ($to=="") {
$to = "info#" . $domain;
}
function int_divide($x, $y) {
if ($x == 0) return 0;
if ($y == 0) return FALSE;
return ($x - ($x % $y)) / $y;
}
$page = int_divide($rank,10) + 1;
if ($template_fn == "mail_template_nick.html" || $template_fn == "mail_template_chet.html" || "mail_template_salesperson.php")
$subject = $domain." is on Page ".$page." of Google - Want to be #1?";
elseif ($template_fn == "seo_template.html")
$subject = "Outsource your SEO - Lowest rates guaranteed!";
elseif ($template_fn == "adwords_template.html")
$subject = $domain . " - Save your money on Google Adwords";
else $subject = $domain . " is ranked " . $rank . " on Google - Be 1st!";
$message = file_get_contents($template_fn);
/*$message = "<body>
<p>Hi There,</p>
<p>How's your week been so far?</p>
<p>When I Googled "{KEYWORD}", I found {WEBSITE} on page {PAGE}, not on page 1. This means consumers will find your competitors before they find you!</p>
<p>93% of all people, never go past the 1st page of Google, so at this very moment you're losing sales & leads to a competitor. </p>
<p>If you agree your Google exposure needs drastic improvement, please call me for a chat, I'm sure I can give some good, free advice. </p>
<p> </p>
<p><strong>Best Regards,</strong></p>
<p><strong>Kayne Chong </strong><strong>- Business Development Director</strong></p>
<p><strong>Tel:</strong> | <strong>Fax: </strong><br />
<strong>Office:</strong> <br />
<strong>Web:</strong> <a href='http://www.seoagency.com.sg/' target='_blank'><em>www.seoagency.com.sg</em></a><br />
<strong><em>Web marketing that brings BUSINESS to you!</em></strong></p>
</body>";*/
$message = str_replace("{WEBSITE}", $domain , $message);
$message = str_replace("{PAGE}", $page , $message);
//$message = str_replace("{RANK}", $rank , $message);
$message = str_replace("{KEYWORD}", $keywords , $message);
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
// Additional headers
/*$headers .= 'Bcc: ' . $adminEmail . "\r\n";
if ($template_fn == "mail_template_salesperson.php")
{ $headers .= 'From: Kayne - Web Marketing Experts <test#example.com>' . "\r\n";
$headers .= 'Reply-To: test#example.com' . "\r\n";}
elseif ($template_fn == "mail_template_chet.html")
{ $headers .= 'From: Chester - Web Marketing Experts <test#example.com>' . "\r\n";
$headers .= 'Reply-To: test#example.com' . "\r\n";}*/
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$headers .= 'Bcc: ' . $adminEmail . "\r\n";
$headers .= 'From: Info - Web Marketing Experts <test#example.com>' . "\r\n";
$headers .= 'Reply-To: test#example.com' . "\r\n";
if (mail($to, $subject, $message, $headers)) {
echo "Mail successfully sent to $to and $adminEmail";
} else echo "Mail sending failed!";
$qry = "INSERT INTO emdb (domain, keywords, rank, last, count) VALUES ('$domain','$keywords','$rank',CURDATE(), '1')";
mysql_query($qry) or die(mysql_error());
echo "<BR />";
echo "DB updated";
} else {
echo "Domain name $domain has already been processed";
}
?>
Thank you.
Jae
Replace every string concatenation with the "." operator with an array push, for example array [ ] = "foo" and then return a string concatenation implode ( array );
Use ob_start(); to cache the output:
ob_start();
echo $a,$b,$c;
$str = ob_get_contents();
ob_end_clean();
You can optimize if to switch and change the order to your expected result. For example if result a is more likely then result b the condition to catch result a should be the first condition.
Put a primary key and secondary key on your table(s).
1.1) Don't use a glue and don't add the construction of the array to the time. Here is a benchmark for http://www.sitecrafting.com/blog/php-string-concat-vs-array
1.2) http://dan.doezema.com/2011/07/php-output-profiling-echo-vs-concat ( although echo is fastest concat is slower then array and also he uses a glue!
1.3) https://stackoverflow.com/questions 1.4) http://www.sitepoint.com/high-performance-string-concatenation-in-php/
Here are my results (30000 strings, time in milliseconds) (Script is taken from 1.4):
standard: 0.02418089
implode w/ glue: 0.00435901
implode w/o glue: 0.02205801
foreach: 0.02081609
Conclusion: use implode with glue.
Your toHtml() is pointless (not to mention it's implemented poorly hence the low performance), you don't need to convert every unicode character to &#...; notation, just put this in your <head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
and print utf-8 strings as they are, your browser will know how to deal with them.
Related
I have this code in my WordPress plugin, it's supposed to get some data from database and after that send emails to different adresses with a common subject but different email body.
<?php
$pdv_subject = "Confirmation links from" . date('d-m-Y', time());
//
$pdv_message_a = "Salut!\n";
$pdv_email_a = 'user#example.com';
$pdv_headers_a[] = 'Cc: user#example.com';
//
$pdv_message_b = "Ciao!\n";
$pdv_email_b = 'user#example.com';
$pdv_headers_b[] = 'Cc: user#example.com';
//
$pdv_message_p = "Hello!\n";
$pdv_email_p = 'user#example.com';
$pdv_headers_p[] = 'Cc: user#example.com';
//
foreach( $results as $key => $val ){
if(date('d-m-Y', $val['confirmed_at']) === date('d-m-Y', time()) && $val['pco'] === '650'){
$pdv_message_a .= $val['link'] . "\n";
}
//
if(date('d-m-Y', $val['confirmed_at']) === date('d-m-Y', time()) && $val['pco'] === '620'){
$pdv_message_b .= $val['link'] . "\n";
}
//
if(date('d-m-Y', $val['confirmed_at']) === date('d-m-Y', time()) && $val['pco'] === '660' ){
$pdv_message_p .= $val['link'] . "\n";
}
}
In the code I've omitted the wp_mail function, I've done a test and it's working fine. The only problem I have is that the $pdv_message_ that needs to be added inside the if statement will be not added, this will cause that the email will be sent without the links inside the body. I've done a var_dump() and I'm able to see the $val but why the links aren't added to the messages?
Aside from anything, I think I'd lay the code out like this
foreach( $results as $key => $val ){
if(date('d-m-Y', $val['confirmed_at']) === date('d-m-Y', time())) {
switch ($val['pco']) {
case '620':
$pdv_message_b .= $val['link'] . "\n";
break;
case '650':
$pdv_message_a .= $val['link'] . "\n";
break;
case '660':
$pdv_message_p .= $val['link'] . "\n";
break;
}
}
}
(I'm not suggesting this is an answer to your problem, but it looks a lot nicer IMO and saves repeating all those identical if clauses.)
I am trying to receive a loop based generated HTML Table in email but seems like I am getting email but no CSS embedded with it as I am passing the BootStrap library CSS files with the email but it's not getting any CSS at all..So I am wondering that what would be the problem...??
Here is screenshot as :
Here is my whole code as :
<?php
$message .= '<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">';
$message .= '<table class="table table-bordered">';
$message .= '<thead>';
$message .= '<tr>';
$message .= '<th>#</th>';
$message .= '<th>Username</th>';
$message .= '<th>Session From</th>';
$message .= '<th>Session Till</th>';
$message .= '<th>Uptime</th>';
$message .= '<th>Download</th>';
$message .= '<th>Upload</th>';
$message .= '<th>Total Usage</th>';
$message .= '</tr>';
$message .= '</thead>';
$message .= '<tbody>';
function human_filesize($bytes, $decimals = 2) {
$factor = floor((strlen($bytes) - 1) / 3);
if ($factor > 0) $sz = 'KMGT';
return sprintf("%.{$decimals}f ", $bytes / pow(1024, $factor)) . #$sz[$factor - 1] . 'B';
}
if (isset($_GET)) {
$user = $_GET["user"];
}
$x = 1;
$handle = fopen($user, "r");
if ($handle) {
while (($line = fgets($handle)) !== false) {
$split_data = (explode(" ",$line));
if (in_array('customer=admin', $split_data)) {
foreach (array_values($split_data) as $i => $value) {
if (strpos($split_data[$i], 'user=') !== false) {
$username = explode("=", $split_data[$i]);
$username = $username[1];
}
}
foreach (array_values($split_data) as $i => $value) {
if (strpos($split_data[$i], 'from-time=') !== false) {
$from_time = explode("=", $split_data[$i]);
$from_time = $from_time[1];
$from_time = $from_time." ".$split_data[$i+1];
}
}
foreach (array_values($split_data) as $i => $value) {
if (strpos($split_data[$i], 'till-time=') !== false) {
$till_time = explode("=", $split_data[$i]);
$till_time = $till_time[1];
$till_time = $till_time." ".$split_data[$i+1];
}
}
foreach (array_values($split_data) as $i => $value) {
if (strpos($split_data[$i], 'uptime=') !== false) {
$uptime = explode("=", $split_data[$i]);
$uptime = $uptime[1];
$download = explode("=", $split_data[$i+1]);
$download = $download[1];
$upload = explode("=", $split_data[$i+2]);
$upload = $upload[1];
#$total_download += $download;
#$total_upload += $upload;
$total_usage = $total_download+$total_upload;
}
}
$message .= '<tr>';
$message .= '<th scope="row">'.$x.'</th>';
$message .= '<td>'.$username.'</td>';
$message .= '<td>'.$from_time.'</td>';
$message .= '<td>'.$till_time.'</td>';
$message .= '<td>'.$uptime.'</td>';
$message .= '<td>'.human_filesize($download,2).'</td>';
$message .= '<td>'.human_filesize($upload,2).'</td>';
$message .= '<td>'.human_filesize($total_usage,2).'</td>';
$message .= '</tr>';
$x=$x+1;
}
}
fclose($handle);
}
$message .= '</tbody>';
$message .= '</table>';
$to = 'nicefellow1234#gmail.com';
$subject = 'Website Change Reqest';
$headers = "From: " . strip_tags($_POST['req-email']) . "\r\n";
$headers .= "Reply-To: ". strip_tags($_POST['req-email']) . "\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=UTF-8\r\n";
mail($to, $subject, $message, $headers);
?>
As of September 2016, Gmail accepts embedded styles – CSS within <style> tags in the head section of HTML documents.
This is in addition to inline styles, which were previously the only way to apply CSS in Gmail.
At the same time, Google says nothing about support for external styles, which is likely why your Bootstrap styles are failing to load.
https://developers.google.com/gmail/design/
PHPMailer is a good option to send email, and mail() function too, but the thing is that generating dynamic content for the email body, and subject are not the best.
for example I've created a php file with the body templates or a class with the same, but are so difficult to maintain.
What do you recomend for organizing that code?
Is there a Way to create email templates? (like twig).
How do you organize folders and files?
Is there any doc recommendation for that?
thanks for your help
It's no different than what you're already doing in PHP to generate dynamic HTML. Except that instead of sending the generated HTML output via your web server to a client UA, you're sending it to an email UA via an MTA.
20 years ago someone thought to invent a good templating engine to generate dynamic content (it was called PHP). It turns out it's still incredibly useful today.
Let's say you have a template file that looks like this for your email.
<table>
<?php foreach($rows as $row) { ?>
<tr>
<?php foreach($row as $column) { ?>
<td><?=$column?></td>
<?php } ?>
</tr>
<?php } ?>
</table>
Let's say have some templating system that renders these templates with perhaps something like this.
class Template {
protected $templateFile = "";
protected $templateVars = [];
public function __construct($templateFile, Array $templateVars= []) {
$this->templateVars = $templateVars;
$this->templateFile = $templateFile;
}
public function __toString() {
export($this->templateVars, EXTR_SKIP);
ob_start();
include $this->templateFile;
return ob_get_clean();
}
}
Now, you could expand upon this very simple abstraction of templating a bit further to include things like your email subject line, sender email address, etc...
class SendEmail {
public function __construct($to, $subject, $template, Array $data) {
$template = new Template($file, $data); // create the email template
$this->emailBody = (string) $template; // generate the content
$this->to = $to;
$this->subject = $subject;
}
public function send() {
// Send email using PHP mailer or whatever here
}
}
$tempalteContent = mysqli_query($conn, "select * from newsletter_template where name like '%$template%'");
if (mysqli_num_rows($tempalteContent) > 0) {
$validate = 0;
$messageFinal = '';
$message = '';
$row = mysqli_fetch_array($tempalteContent);
$template_id = $row['id'];
$productInc = $row['productsInc'];
$blogInc = $row['blogInc'];
$templateMsg = htmlspecialchars_decode($row['description']);
$divData = '';
$blogData = '';
if ($blogInc == 1 && $productInc == 1) {
/* * Product Query* */
$productQuery = mysqli_query($conn, "select * from newsletter_products where newsletter_tempalte_id = $template_id");
if (mysqli_num_rows($productQuery) > 0) {
$width = '';
$website = "http://demo.com/";
if (mysqli_num_rows($productQuery) > 2) {
$width = '100%';
} else if (mysqli_num_rows($productQuery) > 1) {
$width = '100%';
}
for ($i = 0; $i <= mysqli_num_rows($productQuery); $i++) {
$row[$i] = mysqli_fetch_array($productQuery);
$product_id[$i] = $row[$i]['product_id'];
$productDetails[$i] = mysqli_query($conn, "select * from products where product_id = $product_id[$i]");
if (mysqli_num_rows($productDetails[$i]) > 0) {
$rowproduct[$i] = mysqli_fetch_array($productDetails[$i]);
$productName[$i] = $rowproduct[$i]['product_name'];
$productImg[$i] = $website . $rowproduct[$i]['product_img'];
$productDesp[$i] = htmlspecialchars_decode($rowproduct[$i]['product_desp']);
$divData .= "<div style='width:" . $width . ";float:left;padding:7px;text-align:justify'><span style='width:100%;padding-bottom:5px;float:left'><img src='" . $productImg[$i] . "' width='30%' height='30%' style='max-width:100px;max-height:100px'></span><b style='vertical-align:bottom'>" . $productName[$i] . "</b><span style='font-size:12px;'>" . $productDesp[$i] . "</span></div>";
}
$validate++;
}
}
/* * Blog Query* */
$blogQuery = mysqli_query($conn, "select * from newsletter_blogs where newsletter_template_id = $template_id");
if (mysqli_num_rows($blogQuery) > 0) {
$width = '';
$website = "http://demo.com/";
if (mysqli_num_rows($blogQuery) > 2) {
$width = '100%';
} else if (mysqli_num_rows($blogQuery) > 1) {
$width = '100%';
}
for ($i = 0; $i <= mysqli_num_rows($blogQuery); $i++) {
$row[$i] = mysqli_fetch_array($blogQuery);
$blog_id[$i] = $row[$i]['blog_id'];
$blogDetails[$i] = mysqli_query($conn, "select * from blog where id = $blog_id[$i]");
if (mysqli_num_rows($blogDetails[$i]) > 0) {
$rowblog[$i] = mysqli_fetch_array($blogDetails[$i]);
$blogName[$i] = $rowblog[$i]['title'];
$blogImg[$i] = $website . $rowblog[$i]['img'];
$blogDesp[$i] = htmlspecialchars_decode($rowblog[$i]['desp']);
$blogData .= "<div style='width:100%;float:left;padding:7px;text-align:justify'><span style='width:100%;padding-bottom:5px;float:left'><img src='" . $blogImg[$i] . "' width='30%' height='30%' style='max-width:100px;max-height:100px'></span><b style='vertical-align:bottom'>" . $blogName[$i] . "</b><span style='font-size:12px;'>" . $blogDesp[$i] . "</span></div>";
}
$validate++;
}
}
$message = $templateMsg . $divData . $blogData;
} else if ($productInc == 1 && $blogInc == 0) {
$productQuery = mysqli_query($conn, "select * from newsletter_products where newsletter_tempalte_id = $template_id");
if (mysqli_num_rows($productQuery) > 0) {
$width = '';
$website = "http://demo.com/";
if (mysqli_num_rows($productQuery) > 2) {
$width = '100%';
} else if (mysqli_num_rows($productQuery) > 1) {
$width = '100%';
}
for ($i = 0; $i <= mysqli_num_rows($productQuery); $i++) {
$row[$i] = mysqli_fetch_array($productQuery);
$product_id[$i] = $row[$i]['product_id'];
$productDetails[$i] = mysqli_query($conn, "select * from products where product_id = $product_id[$i]");
if (mysqli_num_rows($productDetails[$i]) > 0) {
$rowproduct[$i] = mysqli_fetch_array($productDetails[$i]);
$productName[$i] = $rowproduct[$i]['product_name'];
$productImg[$i] = $website . $rowproduct[$i]['product_img'];
$productDesp[$i] = htmlspecialchars_decode($rowproduct[$i]['product_desp']);
$divData .= "<div style='width:" . $width . ";float:left;padding:7px;text-align:justify'><span style='width:100%;padding-bottom:5px;float:left'><img src='" . $productImg[$i] . "' width='30%' height='30%' style='max-width:100px;max-height:100px'></span><b style='vertical-align:bottom'>" . $productName[$i] . "</b><span style='font-size:12px;'>" . $productDesp[$i] . "</span></div>";
}
$validate++;
}
}
$message = $templateMsg . $divData;
} else if ($blogInc == 1 && $productInc == 0) {
$blogQuery = mysqli_query($conn, "select * from newsletter_blogs where newsletter_tempalte_id = $template_id");
if (mysqli_num_rows($blogQuery) > 0) {
$width = '';
$website = "http://demo.com/";
if (mysqli_num_rows($blogQuery) > 2) {
$width = '100%';
} else if (mysqli_num_rows($blogQuery) > 1) {
$width = '100%';
}
for ($i = 0; $i <= mysqli_num_rows($blogQuery); $i++) {
$row[$i] = mysqli_fetch_array($blogQuery);
$blog_id[$i] = $row[$i]['blog_id'];
$blogDetails[$i] = mysqli_query($conn, "select * from blog where id = $blog_id[$i]");
if (mysqli_num_rows($blogDetails[$i]) > 0) {
$rowblog[$i] = mysqli_fetch_array($blogDetails[$i]);
$blogName[$i] = $rowblog[$i]['title'];
$blogImg[$i] = $website . $rowblog[$i]['img'];
$blogDesp[$i] = htmlspecialchars_decode($rowblog[$i]['desp']);
$blogData .= "<div style='width:100%;float:left;padding:7px;text-align:justify'><span style='width:100%;padding-bottom:5px;float:left'><img src='" . $blogImg[$i] . "' width='30%' height='30%' style='max-width:100px;max-height:100px'></span><b style='vertical-align:bottom'>" . $blogName[$i] . "</b><span style='font-size:12px;'>" . $blogDesp[$i] . "</span></div>";
}
$validate++;
}
}
$message = $templateMsg . $blogData;
} else {
$message = $templateMsg;
}
$messageFinal = '<div style="width:100%">' . $message . '</div>';
echo $validate;
} else {
echo "Fail";
exit();
}
$subscribers = explode(',', $_POST['subscribers']);
for ($i = 0; $i < count($subscribers); $i++) {
$to = $subscribers[$i];
$subject = $template;
$from = 'demo#demo.com';
// To send HTML mail, the Content-type header must be set
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
// Create email headers
$headers .= 'From: Demo' . "\r\n" .
'Reply-To: Your Email Id' . "\r\n" .
'X-Mailer: PHP/' . phpversion();
// Compose a simple HTML email message
$message = '<!DOCTYPE html><html><body>';
$message .= $messageFinal . $footer;
$message .= '</body></html>';
// Sending email
if (mail($to, $subject, $message, $headers)) {
$validate++;
} else {
$validate = 0;
}
}
I'm trying to send all data from the shopping cart in SimpleCartjs to an email. Basically I prefer to send it to a clients email for confirmation of his order. So for now I got it working, but I cannot seem to send the grandTotal, which is the sum of everything (cost + Tax + Shipping). I am able to echo it to the screen, but when mailing it the grandTotal will not send. Any ideas? here is my code so far. The grandTotal in the end of the body field is just there, But I dont know how to get its value:
$send = $_GET['send'];
$to = 'name#myname.com';
$subject = 'Your Tea shopping Cart';
$content = $_POST;
$body = '';
for($i=1; $i < $content['itemCount'] + 1; $i++) {
$name = 'item_name_'.$i;
$quantity = 'item_quantity_'.$i;
$price = 'item_price_'.$i;
$tax = $_POST['taxRate'];
$ship = $_POST['shipping'];
$total = $content[$quantity]*$content[$price];
$iva = $content[$price]*$tax;
$subtotal = $total + $ship + $iva;
$body .= 'item #'.$i.':';
$body .= $content[$name].'<br>';
$body .= $content[$quantity].'Un.: '.$content[$price].'Euros<br>';
$body .= 'IVA : '.$content[$price]*$tax.'Euros<br>';
$body .= 'Shipping: '. $ship.'Euros<br>';
$body .= 'Total: '.$subtotal.'Euros<br>';
$body .= '------------------------------------<br>';
};
$body .= 'Total: '.$grandTotal;
$headers = 'From: name#myname.com' . "\r\n" .
'Reply-To: name#myname.com' . "\r\n" .
'X-Mailer: PHP/' . phpversion();
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
mail($to, $subject, $body, $headers);
First initialize $grandTotal = 0; before the for-loop.
Then, inside the for-loop, after calculating the subtotal, add $grandTotal = $grandTotal + $subTotal;
A user over at w3schools forums assisted me with some code on using IMAP functions to check my mail inbox on a private server and do what i like with it, i created my own set of functions for posting the e-mail content to a MySQL table.
Could somebody help me find a solution to how can i open the e-mail inbox, check for e-mails in the inbox (There will be only one there because previous emails will be automatically deleted. Define the open e-mail message as $open_email_msg
Allow me to initiate my set of commands for posting the e-mail to a MySQL table, then delete the e-mail and close the inbox?
This is the code the person assisted me with:
<?php
$now = time(); // current time
$mailbox = '{192.168.150.11:143/imap/novalidate-cert}'; // see http://www.php.net/manual/en/function.imap-open.php
$mbox = imap_open($mailbox, 'username', 'password'); // log in to mail server
if (!$mbox)
echo ('Failed opening mailbox<br>' . print_r(imap_errors(), true)); // remove the print_r for production use
else
{
$box = imap_check($mbox); // get the inbox
for ($imap_idx = 1; $imap_idx <= $box->Nmsgs; $imap_idx++) // loop through the messages
{
$headers = imap_headerinfo($mbox, $imap_idx); // http://www.php.net/manual/en/function.imap-headerinfo.php
$raw_headers = imap_fetchheader($mbox, $imap_idx); // http://www.php.net/manual/en/function.imap-fetchheader.php
$selected_headers = '';
$text_part = '';
$html_part = '';
$original_message = imap_body($mbox, $imap_idx); // save the copy of the entire thing, attachments and all
// build selected headers string
for ($ii = 0; $ii < count($headers->from); $ii++)
$selected_headers .= 'From: ' . $headers->from[$ii]->mailbox . '#' . $headers->from[$ii]->host . "\n";
for ($ii = 0; $ii < count($headers->to); $ii++)
$selected_headers .= 'To: ' . $headers->to[$ii]->mailbox . '#' . $headers->to[$ii]->host . "\n";
for ($ii = 0; $ii < count($headers->cc); $ii++)
$selected_headers .= 'Cc: ' . $headers->cc[$ii]->mailbox . '#' . $headers->cc[$ii]->host . "\n";
for ($ii = 0; $ii < count($headers->bcc); $ii++)
$selected_headers .= 'Bcc: ' . $headers->bcc[$ii]->mailbox . '#' . $headers->bcc[$ii]->host . "\n";
if (!empty($headers->date))
$selected_headers .= 'Date: ' . $headers->date . "\n";
if (!empty($headers->subject))
$selected_headers .= 'Subject: ' . $headers->subject . "\n";
// see below; getMsg uses global variables
getMsg($mbox, $imap_idx);
$text_part = $plainmsg; // text portion of the email
$html_part = $htmlmsg; // html portion of the email
// check for text portion first
$msg_text = trim(strip_tags($plainmsg
Try this code to read emails.
$username="yourusername#yourmailhost.com";
$password="yourPassword123!";
$hostname="{imap.hostinger.com:993/imap/ssl}INBOX";
$imap=imap_open($hostname,$username,$password) or die('Cannot connect: '.imap_last_error());
$message_count = imap_num_msg($imap);
echo "<b>$message_count messages</b><br>";
for ($i = 1; $i <= $message_count; ++$i){
$header = imap_header($imap, $i);
$body = imap_fetchbody($imap, $i, '2');
$prettydate = date("jS F Y", $header->udate);
if(isset($header->from[0]->personal)){
$personal = $header->from[0]->personal;
}else{
$personal = $header->from[0]->mailbox;
}
$subject=$header->Subject;
$email = "$personal <{$header->from[0]->mailbox}#{$header->from[0]->host}>";
echo "On $prettydate, $email said \"$body\".\n";
echo '<br><br>';
}
print_r(imap_errors());
imap_close($imap);
I believe this link will help you as I used this myself and this is properly working for me.
There you can register and download the code, using it is simple.
Or what you can do if you want to get the information of header only is:
$mbox = imap_open("{xyz#abc.com:995/pop3/ssl/novalidate-cert}INBOX", 'abc#xyz.com', 'pass')
or die("can't connect: " . imap_last_error());
$MC = imap_check($mbox);
$result = imap_fetch_overview($mbox,"1:{$MC->Nmsgs}",0);
foreach ($result as $overview) {
echo "#{$overview->msgno} ({$overview->date}) - From: {$overview->from}
{$overview->subject}\n";
echo "<br>";
}