I need to send multiple files attachments existing in database, with this code WORKS TO SEND ONLY ONE FILE (choosing any from loop). But I will need to send more than on file. Please help me in this matter, I really appreciate. Please ask me anything. Thank you.
////////// THE FORM PAGE
<form novalidate="novalidate" action="{$CMS_base_url}admin/employee_view_email.php?id={$id}" method="post" enctype="multipart/form-data">
<input type="hidden" id="id" name="id" value="{$id}" />
{if is_array ($cvs) && $cvs != "" }
<table class="table table-hover">
<thead>
<tr>
<th class="col-md-2">Create date</th>
<th class="col-md-7">Document name / Description</th>
<th class="col-md-3">Select All <input type="checkbox" name="all" id="all" value="1" onclick="checkUncheckAll(this);" /></th>
<th class="col-md-3">Download</th>
</tr>
</thead>
<tbody>
{foreach from=$cvs key=k item=i}
<tr>
<td><em>{$i.createdAt}</em></td>
<td><strong>{$i.title}</a></strong></td>
<td><input type="checkbox" name="txt_existed_cv_attach" id="txt_existed_cv_attach" value="{$i.id}" /></td>
<td>Download</td>
</tr>
{/foreach}
{else}
<tr>
<td>{lang mkey='error' skey='noResult'}</td>
<td>Upload a new document to send by Admin Email {lang mkey='info' skey='fileAttachments'}</td>
<td colspan="2"><input class="btn-u btn-u-dark-blue" type="file" name="txt_cv_attach" id="txt_cv_attach" multiple="multiple"></td>
</tr>
</tbody>
{/if}
</table>
<input type="submit" name="bt_send_atach" value="SEND EMAIL TO ADMIN" class="btn-u btn-u-lg btn-u-dark-blue pull-left" />
</form>
////////// PAGE FOR fetching ('admin/employeeView.tpl') the FORM PAGE
$id = (int)$_GET['id'];
$smarty->assign('id', $id );
$employee = Employee::find_by_id( $id );
require (CMS_LIB_PATH.DS.'class.cv.php');
///... more classes for employee/user to fetching the related page
$cvs = CV::manageEmployeeCV( $id );
if ( is_array($cvs) and !empty($cvs) )
{
$temp = array();
$i=1;
foreach( $cvs as $cv )
{
$showTo = lang('select','cvShowType');
$temp[$i]['id'] = $cv->id;
$temp[$i]['name'] = $cv->originalName;
$temp[$i]['type'] = $cv->fileType;
$temp[$i]['tmp_name'] = CMS_SITE_ROOT.DS.'curriculum_vitae_file'.DS.$cv->fileName;
$temp[$i]['error'] = 0;
$temp[$i]['size'] = $cv->fileSize;
$temp[$i]['title'] = $cv->title;
$temp[$i]['description'] = $cv->description;
$temp[$i]['showTo'] = $showTo[$cv->showTo];
$temp[$i]['defaultCV'] = $cv->defaultCV;
$temp[$i]['createdAt'] = strftime(dateFormat, strtotime($cv->createdAt) );
$temp[$i]['modifyAt'] = strftime(dateFormat, strtotime($cv->modifyAt) );
$temp[$i]['noViews'] = $cv->noViews;
$temp[$i]['employee_id'] = $cv->employeeIDFK;
$i++;
}
$smarty->assign( 'cvs', $temp );
}
$smarty->assign('employee', $employee );
$smarty->assign('lang', $lang);
$smarty->assign( 'message', $session->getMessage() );
$smarty->assign('rendered_page', $smarty->fetch('admin/employeeView.tpl') );
$smarty->display('admin/index.tpl');
$session->unsetMessage();
////////// CLASS.CV.PHP PAGE WITH DATABASE QUERY FOR LINE
public static function getCVByEmployee( $id=0, $employee_id=0 )
{
global $database, $db;
$sql = " SELECT * FROM ". self::$table_name;
$sql .= " WHERE id=".$db->escape_value($id)." AND employeeIDFK=".(int)$employee_id;
$sql .= " LIMIT 1 ";
$result = self::find_by_sql( $sql );
return !empty($result) ? array_shift($result) : false;
}
// .$db->escape_value($id). // Other page with more DATABASE CLASSES
public function escape_value ( $string ){
if( $this->mysqli_real_escape_string ){
if($this->magic_quotes_active){ $string=stripslashes($string); }
$string = mysqli_real_escape_string($this->connection, $string);
}else{
if(!$this->magic_quotes_active){ $string= addslashes($string); }
}
return $string;
}
////////// EMAIL PROCESS PAGE .....admin/employee_view_email.php?id={$id}
$id = (int)$_GET['id'];
$smarty->assign('id', $id );
$employee = Employee::find_by_id( $id );
///... more classes for employee/user data to send my email
include_once CMS_LIB_PATH.DS.'class.cv.php';
$cvFile = $_FILES['txt_cv_attach'];
$cv_already_existed = $_POST['txt_existed_cv_attach'];
if($cv_already_existed != '' )
{
include_once CMS_LIB_PATH.DS.'class.cv.php';
$cvFile = array();
$user_id = $session->getUserID();
$cv_f = CV::getCVByEmployee( $cv_already_existed, $id );
$cvFile['name'] = $cv_f->originalName;
$cvFile['type'] = $cv_f->fileType;
$cvFile['tmp_name'] = CMS_SITE_ROOT.DS.'curriculum_vitae_file'.DS.$cv_f->fileName;
$cvFile['error'] = 0;
$cvFile['size'] = $cv_f->fileSize;
}
else
{
/*
* check for upload file
*/
if( $cvFile['error'] == 4 )
{
$errors[] = lang( 'error', 'noCVFileApplication');
}
if( $cvFile['error'] == 0 )
{
$ext = end(explode(".", basename($cvFile['name']) ));
$ext = strtolower($ext);
if( !in_array($ext, $allowed_files) )
{
$e = lang('error', 'fileNotAllowed');
$e = str_replace('#file_name#', basename($cvFile['name']) , $e );
$errors[] = $e;
}
if($cvFile['size'] > max_upload_cv_size )
{
$errors[] = lang('error', 'max_file_size');
}
}
}
if( $employee)
{
$full_name = $employee->full_name();
$from = array("email" => no_reply_email, "name" => $full_name );
include CMS_LANGUAGE.DS.'emailTemplate.php';
//send email to admin
$to = array("email" => notify_email, "name" => site_name );
$emailTemplate = lang('email_template','notify_candidate_view_email');
$subject = $emailTemplate['subject'];
$body = $emailTemplate['body'];
$body = str_replace( "#full_name#", $full_name , $body );
$body = str_replace( "#firstName#", $employee->firstName , $body );
$body = str_replace( "#middleName#", $employee->middleName, $body );
$body = str_replace( "#surname#", $employee->surname, $body );
$body = str_replace( "#address#", $employee->address, $body );
$body = str_replace( "#cv_title#", $cv_f->originalName, $body );
$body = str_replace( "#cv_type#", $cv_f->fileType, $body );
$body = str_replace( "#user_id#", $user_id , $body );
$emailBody= array('html' => $body, 'plain' => $body );
$mail = sendMail( $from, $to, $subject, $emailBody, $cvFile);
unset( $_SESSION['account'] );
$message = '<div class="alert success">'.lang('success','email_send_to_admin').'</div>';
}
else
{
$message = lang( 'error', 'errorHead' );
$message .= "<ul> <li />";
$message .= join(" <li /> ", $employee->errors );
$message .= "</ul>";
$message = "<div class='alert error'>".$message."</div>";
}
$smarty->assign( 'cvs', $temp );
$smarty->assign('employee', $employee );
$smarty->assign('lang', $lang);
$session->setMessage( $message );
redirect_to( CMS_BASE_URL . 'admin/employee_view.php?id='.$id );
exit;
////////// SEND EMAIL CLASS PAGE
function sendMail( $from='', $to='', $subject='', $message='', $cvFile='', $clFile='' )
{
global $smarty;
if( $cvFile || !empty($cvFile) || is_array($cvFile) )
{
$CV_temp_path = $cvFile['tmp_name'];
$CV_filename = basename($cvFile['name']);
$CV_type = $cvFile['type'];
$CV_size = $cvFile['size'];
}
if( mail_type == 1 )
{
$mail->IsSMTP();
$mail->Host = "ukm3.siteground.biz";
$mail->Port = "465";
$mail->SMTPSecure = "ssl";
$mail->SMTPAuth = true;
$mail->Username = "admin username";
$mail->Password = "password";
}
try {
$mail->AddAddress($to_email, $to_name);
$mail->SetFrom($from_email, $from_name); //email, name
$mail->Sender=$from_email;
$mail->Subject = $subject;
$mail->AltBody = $plain;
$mail->MsgHTML($html);
if( !empty($cvFile) && is_array($cvFile) && !empty($CV_filename) )
{
$mail->AddAttachment($CV_temp_path, $CV_filename, "base64", $CV_type); // attachment
}
return $mail->Send();
}
catch (phpmailerException $e)
{
echo $e->errorMessage(); //error messages from PHPMailer
die;
}
catch (Exception $e)
{
echo $e->getMessage(); //error messages from anything else!
die;
}
}
It is hard to judge all your code (also because things are included that I don't know), but it looks like here is the problem:
if( !empty($cvFile) && is_array($cvFile) && !empty($CV_filename) )
{
$mail->AddAttachment($CV_temp_path, $CV_filename, "base64", $CV_type); // attachment
}
You want multiple attachment added, not 1.
You give the array $cvFile (poorly named. Name it something like $cvFileArr to make it clear. Now it looks like a single name/path).
SO I expect you need some looping over the values, like this (not tested):
if( !empty($cvFile) && is_array($cvFile) && !empty($CV_filename) ) {
foreach($cvFile as $oneFile){
$mail->AddAttachment($CV_temp_path, $oneFile, "base64", $CV_type); // attachment
}
}
But it is hard to tell exactly. But I expect you need to $mail->AddAttachment for each file you have.
Related
can someone help me a bit with PhpMailer form? I'm not a php dev and i'm a bit lost, mostly because I have no idea how to debug it.
Tips how to debug such scripts are very welcome! (I don't know how to do it in localhost and I host it in a web shared host so I cannot ssh the server)
This is the script:
I have a multiple step form from Frontend which has also recaptcha, so the script include validation of different form steps and recaptcha validation.
<?php
require_once("/PHPMailer/PHPMailer.php");
use PHPMailer\PHPMailer\PHPMailer;
$t_mailer = new PHPMailer;
$t_mailer->SMTPAuth = true;
$t_mailer->Username = "myemail#gmail.com"; // gmail username
$t_mailer->Password = "****"; //gmail password
$t_mailer->SMTPSecure = 'tls';
$t_mailer->Port = 587;
$t_mailer->setFrom("myemail#gmail.com", "Name for the owner of the Account");
//$t_mailer->addAddress("myemail#gmail.com", "Name for who is being sent the email.");
$t_mailer->Subject = "Project request from ECA";
$t_mailer->Body = "This will be the message body that is sent.";
// $recipient = 'myemail#gmail.com'; // Enter the recipient's email address here.
// $subject = 'Project request from ECA'; // Enter the subject of the email here.
$success = 'Your message was sent successful. Thanks.';
$error = 'Sorry. We were unable to send your message.';
$invalid = 'Validation errors occurred. Please confirm the fields and submit it again.';
if ( ! empty( $_POST ) ) {
require_once('recaptcha.php');
if( isset( $_POST['email'] ) ) {
$from = filter_var( $_POST['email'], FILTER_VALIDATE_EMAIL );
} else {
$from = null;
}
if( isset( $_POST['step'] ) ) {
$step = $_POST['step'];
} else {
$step = 'send';
}
if ( ! empty( $_POST['reCAPTCHA'] ) ) {
if ( ! empty( $reCAPTCHA['success'] ) ) {
$errCaptcha = '';
} else {
$errCaptcha = true;
}
} else {
$errCaptcha = '';
}
$errFields = array();
foreach( $_POST as $key => $value ) {
if ( $key != 'section' && $key != 'reCAPTCHA' ) {
if ( $key == 'email' ) {
$validation = filter_var( $_POST[$key], FILTER_VALIDATE_EMAIL );
} else {
$validation = ! empty( $_POST[$key] );
}
if ( ! $validation ) {
$errFields[$key] = true;
}
}
}
if ( empty( $errCaptcha ) && count( $errFields ) === 0 && $step === 'send' ) {
$header = "From: " . $from . " <" . $from . ">" . "\r\n";
$header .= "MIME-Version: 1.0\r\n";
$header .= "Content-type: text/html\r\n";
$body = '<table style="padding: 35px; background-color: #f5f5f5"; font-family: Roboto, sans-serif; font-size: 1rem; text-align: left; border-radius: 4px>';
$body .= '<tr><th style="font-size: 1.5rem; font-weight: 600; color: #1E50BC">'.$subject.'</th></tr>';
$body .= '<tr></td>';
foreach( $_POST as $key => $value ) {
if ( $key != 'section' && $key != 'reCAPTCHA' ) {
$body .= '<p><b>' . str_replace( '-', ' ', ucfirst( $key ) ) . '</b>: ' . $value . '</p>';
}
}
$body .= '</td></tr>';
$body .= '</table>';
$t_mailer->Body = $body;
$t_mailer->addAddress($from, 'who send the email');
// $mail = mail( $recipient, $subject, $body, $header );
// $mail
if ( $t_mailer->send() ) {
$response = array(
'status' => 'success',
'info' => $success
);
print_r( json_encode( $response ) );
} else {
$response = array(
'status' => 'fail',
'info' => $error
);
print_r( json_encode( $response ) );
}
} else {
$response = array(
'status' => 'invalid',
'info' => $invalid,
'captcha' => $errCaptcha,
'fields' => $errFields,
'errors' => count( $errFields )
);
print_r( json_encode( $response ) );
}
exit;
}
I'm sure PhpMailer works with my host and my server because I tried a very simple script that send an email from root and it worked. (I got the email in my gmail inbox)
But This script is in another folder, not root, even tho they all have same folder/files permission (not sure if is relevant, but better specify!)
Several things not quite right here.
When you're using PHPMailer without composer, you need to load all the classes it needs yourself, so add:
require_once '/PHPMailer/SMTP.php';
require_once '/PHPMailer/Exception.php';
You are setting some SMTP config properties, but not actually telling PHPMailer to use SMTP, so add this:
$t_mailer->isSMTP();
You're sending from a gmail address, which means you must send through gmail's servers (or you will fail SPF checks), but you have not specified a server to send through, so set this:
$t_mailer->Host = 'smtp.gmail.com';
Your content is in HTML, but you're not asking PHPMailer to send it as HTML:
$t_mailer->isHTML();
You don't need any of that stuff you're doing with $header; PHPMailer does all that for you.
Rather than going any further, I'd recommend basing your code on the gmail example provided with PHPMailer, and if you run into any other issues, refer to the PHPMailer troubleshooting guide and search on here.
I have written an application in CakePHP. I am facing an issue. Sometimes it happens that when an order is placed, it's not reflecting in database, but I am both getting an email and it's reflecting in my PayU account dashboard that someone has placed an order with x amount.
Below is my code. What is wrong?
if(!empty($this->data)){
$data = $this->data;
$userInfo = $this->User->find('first',array('conditions'=>array('User.id'=>$userID)));
$sales_rep_email = $userInfo["User"]["sales_rep_email"];
$user_email = $userInfo["User"]["primary_contact_email"];
$virtual_account = $userInfo["User"]["virtual_account"];
if($data['payment_method']=="RTGS Payment"){
$orderData['Order']['invoice_no'] = 0;
$orderData['Order']['invoice_prefix'] = "INV-2015-00";
$orderData['Order']['user_id'] = $userInfo['User']['id'];
$orderData['Order']['name'] = $userInfo['User']['name'];
$orderData['Order']['email'] = $userInfo['User']['primary_contact_email'];
$orderData['Order']['phone'] = $userInfo['User']['primary_contact_number'];
$orderData['Order']['billing_address'] = $userInfo['User']['address'].", ".$userInfo['User']['city'].", ".$userInfo['User']['district'].", ".$userInfo['User']['state']."-".$userInfo['User']['pin_code'];
$orderData['Order']['order_item_count'] = $shop['Order']['quantity'];
$orderData['Order']['shipping'] = $data['shipping_method'];
$orderData['Order']['total'] = $shop['Order']['total'];
$orderData['Order']['payment_method'] = $data['payment_method'];
if($data['shipping_method']=="Express Delivery"){
$orderData['Order']['delivery_charges'] = 400;
}
if($data['payment_method']=="RTGS Payment"){
$orderData['Order']['status'] = 'open';
$orderData['Order']['temp_status'] = 'rtgs';
}else if($data['payment_method']=="COD"){
$orderData['Order']['status'] = 'open';
$orderData['Order']['temp_status'] = 'cod';
$orderData['Order']['customer_status'] = 'unconfirmed';
}else{
$orderData['Order']['status'] = 'open';
$orderData['Order']['temp_status'] = 'open';
}
$this->Order->save($orderData);
$id = $this->Order->getLastInsertId();
$orderupdateData['Order']['orderid'] = date("Y").date("m").'-'.$id;
$orderupdateData['Order']['temporary_order'] = "TO".'-'.$id;
$orderupdateData['Order']['id'] = $id;
$this->Order->save($orderupdateData);
$orderItemData = array();
foreach($shop['OrderItem'] as $key=>$item){
$quantityNewCheckOut = 0;
if(!empty($data['payment_method'])){
$this->manageInventory($item['Product']['smb_code'],$item['quantity']);
}
$orderItemData['OrderItem']['order_id'] = $id;
$orderItemData['OrderItem']['sku_id'] = $key;
$inventoryData = $this->Inventory->find("first",array("conditions"=>array("Inventory.smb_item_code"=>$item['Product']['smb_code'])));
$quantityNewCheckOut = (int)$inventoryData["Inventory"]["quantity"];
if($quantityNewCheckOut<=0){
$orderItemData["OrderItem"]["mod_name"] = "back";
}else if($quantityNewCheckOut>0){
$orderItemData["OrderItem"]["mod_name"] = "available";
}
$orderItemData['OrderItem']['name'] = $item['Product']['smb_code'];
$orderItemData['OrderItem']['quantity'] = $item['quantity'];
$orderItemData['OrderItem']['price'] = $item['price'];
if(!empty($item['discount_amount'])){
$orderItemData['OrderItem']['discount_amount'] = $item['discount_amount'];
}
$orderItemData['OrderItem']['subtotal'] = $item['subtotal'];
$orderItemData['OrderItem']['status'] = "open";
$this->OrderItem->save($orderItemData);
$this->OrderItem->create();
unset($orderItemData);
}
$orderDetails = $this->OrderItem->find("all",array("conditions"=>array("OrderItem.order_id"=>$id),'recursive'=>2));
$content = "<b>Order Date:</b>".date("d F Y H:i:s")."<br/>";
$content .= "<b>Temporary Order Number:</b>"."TO".'-'.$id."<br/><br/><br/>";
$content .= "<table border='1'><thead><th>Company Name</th><th>Brand</th><th>SMB Item Code</th><th>Mfg Code</th><th>Product Description</th><th>UOM</th><th>MRP</th><th>Unit Price</th><th>Qty</th><th>Subtotal</th><th>Tax%</th><th>Total</th></thead><tbody>";
foreach($orderDetails as $orderItem){
$content .= "<tr>";
$content .= "<td>".$orderItem["Sku"]["Company"]["name"]."</td>";
$content .= "<td>".$orderItem["Sku"]["Brand"]["name"]."</td>";
$content .= "<td>".$orderItem["Sku"]["smb_code"]."</td>";
$content .= "<td>".$orderItem["Sku"]["title"]."</td>";
$content .= "<td>".$orderItem["Sku"]["description"]."</td>";
$content .= "<td>".$orderItem["Sku"]["uom"]."</td>";
$content .= "<td>"."Rs.".$orderItem["Sku"]["mrp"]."</td>";
$content .= "<td>"."Rs.".$orderItem["OrderItem"]["price"]."</td>";
$content .= "<td>".$orderItem["OrderItem"]["quantity"]."</td>";
$content .= "<td>"."Rs.".sprintf('%01.2f', $orderItem["OrderItem"]["price"] * $orderItem["OrderItem"]["quantity"])."</td>";
$content .= "<td>".$orderItem["Sku"]["Product"]["tax"]."</td>";
$content .= "<td>"."Rs.".$orderItem["OrderItem"]["subtotal"]."</td>";
$content.= "</tr>";
}
if($data['shipping_method']=="Express Delivery"){
$totalAmount = ($orderItem["Order"]["total"])+400;
$content .= "<tr><td style='text-align:right' colspan='10'>Delivery Charges:</td><td style='text-align:right'colspan='2'>"."Rs. 400</td></tr>";
$content .= "<tr><td style='text-align:right' colspan='10'>Grand Total:</td><td style='text-align:right'colspan='2'>"."Rs. ".$totalAmount."</td></tr>";
}else{
$content .= "<tr><td style='text-align:right' colspan='10'>Grand Total:</td><td style='text-align:right'colspan='2'>"."Rs. ".$orderItem["Order"]["total"]."</td></tr>";
}
$content .= "</tbody></table>";
$emailTemplate = $this->EmailTemplate->find('first',array('conditions'=>array('EmailTemplate.id'=>'23')));
$emailContent = $emailTemplate['EmailTemplate']['html_content'];
$subject = $emailTemplate['EmailTemplate']['subject']."TO".'-'.$id;
$template_info = str_replace(array('$temp_order','$virtual_id','$content','$salesrep'),array("TO".'-'.$id,$virtual_account,$content,$sales_rep_email),$emailContent);
$email = new CakeEmail();
$email->template('email_template');
$email->emailFormat('both');
$email->viewVars(array('emailContent' => $template_info));
$to = array($user_email);//$to = '';
$from = '';
$email->to($to);
$email->bcc("");
$email->cc($sales_rep_email);
$email->from(array($from=>''));
$email->subject($subject);
$email->smtpOptions = array(
'port'=>'25',
'timeout'=>'30',
'host' => '',
'username'=>'',
'password'=>'',
);
//Set delivery method
$email->delivery = 'smtp';
//pry($email);
$email->send();
$this->redirect(array('action'=>"successOrderRTGS"));
}else{
$paymentMethod = $data['payment_method'];
$shippingMethod = $data['shipping_method'];
if(!empty($paymentMethod)){
$this->Session->write("User.payment_method",$paymentMethod);
$this->Session->write("User.shipping_method",$shippingMethod);
}
$orderData['Order']['total'] = $shop['Order']['total'];
if($data['shipping_method']=="Express Delivery"){
$orderData['Order']['delivery_charges'] = 400;
$amount =($shop['Order']['total'])+400;
}else{
$amount =($shop['Order']['total']);
}
$this->pay_page( array ( 'key' => '', 'txnid' => uniqid( 'test' ), 'amount' => $amount,
'firstname' => $userInfo['User']['name'], 'email' => $userInfo['User']['primary_contact_email'], 'phone' => $userInfo['User']['primary_contact_number'],
'productinfo' => 'Product Info', 'surl' => 'payment_success', 'furl' => 'payment_failure'), '' );
}
}
The reason your code is sending out the email despite not saving the Order data in the database is because you are not checking whether the save() is successful or not. It's probably failing due to validation errors, but your code won't do anything about it.
The proper way of handling this is by wrapping the save() method inside an if condition:
if ($this->Order->save($orderData)) {
//send email
//redirect
} else {
Debugger::log($this->Order->validationErrors);
$this->Flash->set('Order could not be saved');
}
You should also refactor your action to reduce its size. The main purpose of using a MVC framework is to make life easier by separating business logic, control logic and views. If you find yourself writing HTML in your controller, you are probably doing something wrong.
Interesting read: Fat models, skinny controllers and the MVC design pattern
I am having problems sending emails using the PHPMailer class for my registration form. I was wondering if the below code could be changed into a normal Mail class please.
<?php
require_once('PHPMailer_v5.1/PHPMailer.php');
class Email {
public $objUrl;
private $objMailer;
public function __construct($objUrl = null) {
$this->objUrl = is_object($objUrl) ? $objUrl : new Url();
$this->objMailer = new PHPMailer();
$this->objMailer->IsSMTP();
$this->objMailer->SMTPAuth = true;
$this->objMailer->SMTPKeepAlive = true;
$this->objMailer->SMTPSecure = 'ssl';
$this->objMailer->Host = "smtp.gmail.com";
$this->objMailer->Port = 465;
$this->objMailer->Username = "email here";
$this->objMailer->Password = "password here";
$this->objMailer->SetFrom("email here", "name here");
$this->objMailer->AddReplyTo("email here ", "name here");
}
public function process($case = null, $array = null) {
if (!empty($case)) {
switch($case) {
case 1:
// add url to the array
$link = "<a href=\"";
$link .= SITE_URL.$this->objUrl->href('activate', array('code', $array['hash']));
$link .= "\">";
$link .= SITE_URL.$this->objUrl->href('activate', array('code', $array['hash']));
$link .= "</a>";
$array['link'] = $link;
$this->objMailer->Subject = "Activate your account";
$this->objMailer->MsgHTML($this->fetchEmail($case, $array));
$this->objMailer->AddAddress(
$array['email'],
$array['first_name'].' '.$array['last_name']
);
break;
}
// send email
if ($this->objMailer->Send()) {
$this->objMailer->ClearAddresses();
return true;
}
return false;
}
}
public function fetchEmail($case = null, $array = null) {
if (!empty($case)) {
if (!empty($array)) {
foreach($array as $key => $value) {
${$key} = $value;
}
}
ob_start();
require_once(EMAILS_PATH.DS.$case.".php");
$out = ob_get_clean();
return $this->wrapEmail($out);
}
}
public function wrapEmail($content = null) {
if (!empty($content)) {
return "<div style=\"font-family:Arial,Verdana,Sans-serif;font-size:12px;color:#333;line-height:21px;\">{$content}</div>";
}
}
}
Any help is much appreciated
Thanks
I have tried to amend the code to the below code but all I get is a blank screen. I have checked on firefox and no error messages are displayed. Can anyone help fix the problem.
Thank you
<?php
//require_once('PHPMailer_v5.1/PHPMailer.php');
class Email {
public $objUrl;
//private $objMailer;
public function __construct($objUrl = null) {
$this->objUrl = is_object($objUrl) ? $objUrl : new Url();
$to = "qakbar26#gmail.com";
$headers = 'MIME-Version: 1.0'."\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1'."\r\n";
$headers .= "From: qakbar26#gmail.com";
}
public function process($case = null, $array = null) {
if (!empty($case)) {
switch($case) {
case 1:
// add url to the array
$link = "<a href=\"";
$link .= SITE_URL.$this->objUrl->href('activate', array('code', $array['hash']));
$link .= "\">";
$link .= SITE_URL.$this->objUrl->href('activate', array('code', $array['hash']));
$link .= "</a>";
$array['link'] = $link;
$subject = "Activate your account";
$message($this->fetchEmail($case, $array));
$address(
$array['email'],
$array['first_name'].' '.$array['last_name']
);
break;
}
// send email
if ($send()) {
$this->ClearAddresses();
return true;
}
return false;
}
}
public function fetchEmail($case = null, $array = null) {
if (!empty($case)) {
if (!empty($array)) {
foreach($array as $key => $value) {
${$key} = $value;
}
}
ob_start();
require_once(EMAILS_PATH.DS.$case.".php");
$out = ob_get_clean();
return $this->wrapEmail($out);
}
}
public function wrapEmail($content = null) {
if (!empty($content)) {
return "<div style=\"font-family:Arial,Verdana,Sans-serif;font-size:12px;color:#333;line-height:21px;\">{$content}</div>";
}
}
}
Just an update I have manged to get the PHPMailer ot work after I commented out the below line of code.
$this->objMailer->IsSMTP();
Not sure why but the IsSMTP(); is not letting the emails go through.
I have this class for show error with session method using PHP.
class Messages {
//-----------------------------------------------------------------------------------------------
// Class Variables
//-----------------------------------------------------------------------------------------------
var $msgId;
var $msgTypes = array( 'help', 'info', 'warning', 'success', 'danger' );
var $msgClass = 'alert';
var $msgWrapper = " <div class='alert %s-%s flashit'>
<button class='close' aria-hidden='true' data-dismiss='alert' type='button'>×</button>
<p><i style='vertical-align: middle;' class='%s icon-2x'></i> %s</p>
</div>";
var $msgBefore = '';
var $msgAfter = "";
public function __construct() {
// Generate a unique ID for this user and session
$this->msgId = md5(uniqid());
// Create the session array if it doesnt already exist
if( !array_key_exists('flash_messages', $_SESSION) ) $_SESSION['flash_messages'] = array();
}
public function add($type, $message, $redirect_to=null) {
if( !isset($_SESSION['flash_messages']) ) return false;
if( !isset($type) || !isset($message[0]) ) return false;
// Replace any shorthand codes with their full version
if( strlen(trim($type)) == 1 ) {
$type = str_replace( array('h', 'i', 'w', 'e', 's'), array('help', 'info', 'warning', 'danger', 'success'), $type );
$icon = str_replace( array('h', 'i', 'w', 'e', 's'), array('fa-help', 'fa-info', 'fa-warning', 'fa-danger', 'fa-success'), $type );
// Backwards compatibility...
} elseif( $type == 'information' ) {
$type = 'info';
$icon = 'fa-info';
}
// Make sure it's a valid message type
if( !in_array($type, $this->msgTypes) ) die('"' . strip_tags($type) . '" is not a valid message type!' );
// If the session array doesn't exist, create it
if( !array_key_exists( $type, $_SESSION['flash_messages'] ) ) $_SESSION['flash_messages'][$type] = array();
$_SESSION['flash_messages'][$type][] = $message;
if( !is_null($redirect_to) ) {
header("Location: $redirect_to");
exit();
}
return true;
}
//-----------------------------------------------------------------------------------------------
// display()
// print queued messages to the screen
//-----------------------------------------------------------------------------------------------
public function display($type='all', $print=true) {
$messages = '';
$data = '';
if( !isset($_SESSION['flash_messages']) ) return false;
if( $type == 'g' || $type == 'growl' ) {
$this->displayGrowlMessages();
return true;
}
// Print a certain type of message?
if( in_array($type, $this->msgTypes) ) {
foreach( $_SESSION['flash_messages'][$type] as $msg ) {
$messages .= $this->msgBefore . $msg . $this->msgAfter;
}
$data .= sprintf($this->msgWrapper, $this->msgClass, $type,$icon,$messages);
// Clear the viewed messages
$this->clear($type);
// Print ALL queued messages
} elseif( $type == 'all' ) {
foreach( $_SESSION['flash_messages'] as $type => $msgArray ) {
$messages = '';
foreach( $msgArray as $msg ) {
$messages .= $this->msgBefore . $msg . $this->msgAfter;
}
$data .= sprintf($this->msgWrapper, $this->msgClass, $type,$icon,$messages);
}
// Clear ALL of the messages
$this->clear();
// Invalid Message Type?
} else {
return false;
}
// Print everything to the screen or return the data
if( $print ) {
echo $data;
} else {
return $data;
}
}
//..... more
}
Call:
$msg = new Messages();
$msg->add('i', 'This is a Information message!');
echo $msg->display();
Now in Output:
<i style="vertical-align: middle;" class=" icon-2x"></i>
Icon class not printed and empty: class=" icon-2x". how do can i fix this ?
EDit: Indeed i need to print for each type One class name.
I'm relatively new to WordPress and PHP, however I am trying to create my own shortcode plugin, which I have completed and is working.
However if I add more than 1 on the same page in WP, both forms submit and are not exclusive of each other.
I have search around the web, but can't find out how to easily separate the form id's, below is my plugin code:
function wptuts_contact_form_sc($atts, $content = null) {
extract(shortcode_atts(array(
//"email" => get_bloginfo('admin_email'),
"id" => '',
"attachment" => '',
"desc" => '',
"subject" => '',
"label_email" => 'Your E-mail Address',
"label_submit" => 'Submit',
"error_empty" => 'Please fill in all the required fields.',
"error_noemail" => 'Please enter a valid e-mail address.',
"success" => 'Thanks, your voucher has been sent to '
), $atts));
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$error = false;
$required_fields = array("email");
foreach ($_POST as $field => $value) {
if (get_magic_quotes_gpc()) {
$value = stripslashes($value);
}
$form_data[$field] = strip_tags($value);
}
foreach ($required_fields as $required_field) {
$value = trim($form_data[$required_field]);
if(empty($value)) {
$error = true;
$result = $error_empty;
}
}
if(!is_email($form_data['email'])) {
$error = true;
$result = $error_noemail;
}
if ($error == false) {
$email_subject = "Eurest Voucher - " . $desc;
$email_message = "Hi, Your requested voucher/offer is attached to this email.";
$headers = "From: Eurest Vouchers <Vouchers#eurestfood.com>\n";
$headers .= "Content-Type: text/plain; charset=UTF-8\n";
$headers .= "Content-Transfer-Encoding: 8bit\n";
$attachments = array(WP_CONTENT_DIR . $attachment);
$email = $form_data['email'];
wp_mail($email, $email_subject, $email_message, $headers, $attachments);
$result = $success . $form_data['email'];
$sent = true;
}
}
if($result != "") {
$info = '<div class="info">'.$result.'</div>';
}
$email_form = '<form class="contact-form" method="post" id="'.$id.'" action="'.get_permalink().'">
<div>
<label for="cf_email">'.$label_email.':</label>
<input type="text" name="email" id="cf_email" size="50" maxlength="50" value="'.$form_data['email'].'" /><input type="submit" value="'.$label_submit.'" name="send" id="cf_send" />
</div>
</form>';
if($sent == true) {
return $info;
} else {
return $info.$email_form;
}
} add_shortcode('emailattachment', 'wptuts_contact_form_sc');
If someone can help that would be appreciated.
Thanks,
Steve
I am pretty sure you've forgotten the last attribute in the function shortcode_atts, even if it's optionnal, you need to call it.
Also, is there some code missing ?
edit : you need to id your forms otherwise the function will pick up the datas twice. call the second shortcode giving the value 'second' to teh variable $num_f like so [wptuts_contact_form_sc -your bunch of vars here- num_f="second"]
function wptuts_contact_form_sc($atts, $content = null) {
extract(shortcode_atts(array(
//"email" => get_bloginfo('admin_email'),
"id" => '',
"attachment" => '',
"desc" => '',
"subject" => '',
"label_email" => 'Your E-mail Address',
"label_submit" => 'Submit',
"error_empty" => 'Please fill in all the required fields.',
"error_noemail" => 'Please enter a valid e-mail address.',
"success" => 'Thanks, your voucher has been sent to ',
"num_f" => 'first'
), $atts));
if ($_SERVER['REQUEST_METHOD'] == 'POST' && $num_f == 'second') {
$error = false;
$required_fields = array("email");
foreach ($_POST as $field => $value) {
if (get_magic_quotes_gpc()) {
$value = stripslashes($value);
}
$form_data[$field] = strip_tags($value);
}
foreach ($required_fields as $required_field) {
$value = trim($form_data[$required_field]);
if(empty($value)) {
$error = true;
$result = $error_empty;
}
}
if(!is_email($form_data['email'])) {
$error = true;
$result = $error_noemail;
}
if ($error == false) {
$email_subject = "Eurest Voucher - " . $desc;
$email_message = "Hi, Your requested voucher/offer is attached to this email.";
$headers = "From: Eurest Vouchers <Vouchers#eurestfood.com>\n";
$headers .= "Content-Type: text/plain; charset=UTF-8\n";
$headers .= "Content-Transfer-Encoding: 8bit\n";
$attachments = array(WP_CONTENT_DIR . $attachment);
$email = $form_data['email'];
wp_mail($email, $email_subject, $email_message, $headers, $attachments);
$result = $success . $form_data['email'];
$sent = true;
}
}
if($result != "") {
$info = '<div class="info">'.$result.'</div>';
}
$email_form = '<form class="contact-form" method="post" id="'.$id.'" action="'.get_permalink().'">
<div>
<label for="cf_email">'.$label_email.':</label>
<input type="text" name="email" id="cf_email" size="50" maxlength="50" value="'.$form_data['email'].'" /><input type="submit" value="'.$label_submit.'" name="send" id="cf_send" />
</div>
</form>';
if($sent == true) {
return $info;
} else {
return $info.$email_form;
}
} add_shortcode('emailattachment', 'wptuts_contact_form_sc');
To have more than two forms, you can either do it manually by calling the third block 'trird' and so on, but that's not very good practice to be honest...
If I were you I would change your code at the core, create a function that would return the form with a hidden field like so : <input type"hidden" name="hidden" value=" . $nf . "> and then instead of controling $_SERVER['REQUEST_METHOD'], you'd control the value of $_POST['n'] after checking if it's set ofc.
Here's the code I came up with :
<?php
function wptuts_contact_form_sc($atts, $content = null) {
extract(shortcode_atts(array(
//"email" => get_bloginfo('admin_email'),
"id" => '',
"attachment" => '',
"desc" => '',
"subject" => '',
"label_email" => 'Your E-mail Address',
"label_submit" => 'Submit',
"error_empty" => 'Please fill in all the required fields.',
"error_noemail" => 'Please enter a valid e-mail address.',
"success" => 'Thanks, your voucher has been sent to ',
"nf" => '1'
), $atts));
if (isset($_POST['hidden'])) {
$hidden = $_POST['hidden'];
$error = false;
$required_fields = array("email");
foreach ($_POST as $field => $value) {
if (get_magic_quotes_gpc()) {
$value = stripslashes($value);
}
$form_data[$field] = strip_tags($value);
}
foreach ($required_fields as $required_field) {
$value = trim($form_data[$required_field]);
if(empty($value)) {
$error = true;
$result = $error_empty;
}
}
if(!is_email($form_data['email'])) {
$error = true;
$result = $error_noemail;
}
if ($error == false) {
$email_subject = "Eurest Voucher - " . $desc;
$email_message = "Hi, Your requested voucher/offer is attached to this email.";
$headers = "From: Eurest Vouchers <Vouchers#eurestfood.com>\n";
$headers .= "Content-Type: text/plain; charset=UTF-8\n";
$headers .= "Content-Transfer-Encoding: 8bit\n";
$attachments = array(WP_CONTENT_DIR . $attachment);
$email = $form_data['email'];
wp_mail($email, $email_subject, $email_message, $headers, $attachments);
$result = $success . $form_data['email'];
$sent = true;
}
} else {
$hidden = $_POST['hidden'];
}
for ($i = 1; $i <= $nf; $i++) {
if($result != "" && $i == $hidden) {
$info = '<div class="info">'.$result.'</div>';
}
$email_form = '<form class="contact-form" method="post" id="'.$id.'" action="'.get_permalink().'">
<div>
<label for="cf_email">'.$label_email.':</label>
<input type="hidden" name="hidden" value="' . $nf . '">
<input type="text" name="email" id="cf_email" size="50" maxlength="50" value="'.$form_data['email'].'" /><input type="submit" value="'.$label_submit.'" name="send" id="cf_send" />
</div>
</form>';
if($sent == true) {
return $info;
} else {
return $info . $email_form;
}
}
} add_shortcode('emailattachment', 'wptuts_contact_form_sc');
?>
Let me know if it works, (or does not) I obviously couldnt test it so there might be somehting wrong, in which case I just hope you got the whole idea behind it.