PHPMailer - How do I unlink files in temp dir.? - phpmailer

I am looping through the files array as shown in the middle chunk of code, rest of the code is just for better context.
$email = new PHPMailer();
$email->From = 'John#example.com';
$email->FromName = 'John Doe';
$email->Subject = $name_talent;
$body = '<strong>ADDRESS</strong> : ' .$address_talent.'<br><br>';
if ($_FILES) {
foreach ($_FILES as $file => $array) {
$tmp_path = $_FILES[$file]['tmp_name'];
$tmp_name = basename($_FILES[$file]['name']);
$email->AddAttachment($tmp_path, $tmp_name);
}
}
$email->Body = $body;
$email->IsHTML(true);
$email->AddAddress( '######gmail.com' );
$email->Send();
This sends the attachments with values in the $body as well. Now, I would like to unlink the files either after the mail is sent or the attachments are successful. As inspired from this answer, If I do it like this below, no files are attached and any variables set for the $body eg. $address_talent do not appear in the email.
if ($_FILES) {
foreach ($_FILES as $file => $array) {
$tmp_path = $_FILES[$file]['tmp_name'];
$tmp_name = basename($_FILES[$file]['name']);
if($email->AddAttachment($tmp_path, $tmp_name)){
unlink("$tmp_path");
}
}
}

Related

How to send customer renewal order to secondary email in Woocommerce subscription

I want to send the renewal order email to a secondary user email(which i have added in user-edit page using ACF).
I have tried many methods,woocommerce_subscription_payment_complete is also not working for me.
The following code i have tried:
add_action( 'woocommerce_order_status_completed', 'action_on_order_status_completed', 20, 2 );
function action_on_order_status_completed( $order_id, $order ){
$order = new WC_Order($order_id);
// Get the user ID from WC_Order methods
$user_id = $order->get_user_id(); // or $order->get_customer_id();
$secondary_recipient = get_field('secondary_email', 'user_'.$user_id );
$subscriptions_ids = wcs_get_subscriptions_for_order( $order_id, array( 'order_type' => 'any' ) );
// We get all related subscriptions for this order
foreach( $subscriptions_ids as $subscription_id => $subscription_obj )
if($subscription_obj->order->id == $order_id) break; // Stop the loop
// $subscription_objc = wcs_get_subscription($subscription_id);
//$userid = $subscription_objc->get_user_id();
$wc_emails = WC()->mailer()->get_emails();
$wc_emails['WCS_Email_Processing_Renewal_Order']->recipient = $secondary_recipient;
$wc_emails['WCS_Email_Processing_Renewal_Order']->trigger($subscription_id);
// $to = $secondary_recipient;
// $subject = "hi";
// $body =$user_id."end".$order_id."hhh".$subscription_id;
// $headers = array('Content-Type: text/html; charset=UTF-8');
// //$headers[] = 'Cc: sarun#cloudspring.in';
// wp_mail( $to, $subject, $body, $headers );
}
FYI:Email is sending if i use the commented wp_mail function.
We can add a secondary email as the recipient, Try the below code tested and it worked.
add_filter( 'woocommerce_email_recipient_customer_completed_renewal_order', 'my_email_recipient_filter_function', 10, 2);
function my_email_recipient_filter_function( $recipient, $order ) {
$user_id = $order->get_user_id(); // or $order->get_customer_id();
$secondary_recipient = get_field('secondary_email', 'user_'.$user_id );
if(! empty($secondary_recipient)){
$recipient = $recipient . ', '. $secondary_recipient;
return $recipient;
}else {
return $recipient;
}
}

Importing images along with other fields (username,subjectname) from excel in laravel

I am using phpspreadsheet. I want to import an excel sheet that have images too, it looks something like this,
I am able to retrieve fields separately and images separately, I want to get them together. Problem I am facing is that Images are being accessed with
$spreadsheet->getActiveSheet()->getDrawingCollection()
and for others field i have to access them like this
$spreadsheet->getRowIterator()
as both of them requires separate loops, should i be merging them into one or what is the right way so that i am able to retrieve both(images and fields) together.
Images retrieve code:
$spreadsheet = IOFactory::load($request->import_file);
$i = 0;
foreach ($spreadsheet->getActiveSheet()->getDrawingCollection() as $key => $drawing) {
if ($drawing instanceof MemoryDrawing) {
ob_start();
call_user_func(
$drawing->getRenderingFunction(),
$drawing->getImageResource()
);
$imageContents = ob_get_contents();
ob_end_clean();
switch ($drawing->getMimeType()) {
case MemoryDrawing::MIMETYPE_PNG :
$extension = 'png';
break;
case MemoryDrawing::MIMETYPE_GIF:
$extension = 'gif';
break;
case MemoryDrawing::MIMETYPE_JPEG :
$extension = 'jpg';
break;
}
} else {
$zipReader = fopen($drawing->getPath(), 'r');
$imageContents = '';
while (!feof($zipReader)) {
$imageContents .= fread($zipReader, 1024);
}
fclose($zipReader);
$extension = $drawing->getExtension();
}
$myFileName = time() .++$i. '.' . $extension;
$imagesCollection['answerImages_'.$key] =$myFileName;
file_put_contents('images/products/' . $myFileName, $imageContents);
$a = Answers::create([
'answerImages'=>$myFileName,
'questionId'=>($key <=4)?1:2,
]);
}
I want to store them into my table in database such that in questionImage column of database it has image name like this
and it is storing it currently but as I mentioned earlier i have to store them separtely
This is how i am storing other fields
$spreadsheet = IOFactory::load($the_file->getRealPath());
$sheet = $spreadsheet->getActiveSheet();
$row_limit = $sheet->getHighestDataRow();
$column_limit = $sheet->getHighestDataColumn();
$row_range = range( 1, $row_limit );
$column_range = range( 'F', $column_limit );
$startcount = 2;
$data = array();
foreach ( $row_range as $row ) {
$data[] = [
'courseName' =>$sheet->getCell( 'A' . $row )->getValue(),
'subjectName' => $sheet->getCell( 'B' . $row )->getValue(),
'question' => $sheet->getCell( 'C' . $row )->getValue(),
'questionImage' => $sheet->getCell( 'D' . $row )->getValue(),
];
$startcount++;
}
DB::table('questions')->insert($data);
How to get them together so that i can store them in one table
you should try maatwebsite/excel package. it will save your time.

Empty PHPExcel file using liuggio/ExcelBundle in Symfony

I have some code that iterates over the rows and columns of an Excel sheet and replaces text with other text. This is done with a service that has the excel file and a dictionary as parameters like this.
$mappedTemplate = $this->get('app.entity.translate')->translate($phpExcelObject, $dictionary);
The service itself looks like this.
public function translate($template, $dictionary)
{
foreach ($template->getWorksheetIterator() as $worksheet) {
foreach ($worksheet->getRowIterator() as $row) {
$cellIterator = $row->getCellIterator();
$cellIterator->setIterateOnlyExistingCells(false); // Loop all cells, even if it is not set
foreach ($cellIterator as $cell) {
if (!is_null($cell)) {
if (!is_null($cell->getCalculatedValue())) {
if (array_key_exists((string)$cell->getCalculatedValue(), $dictionary)) {
$worksheet->setCellValue(
$cell->getCoordinate(),
$dictionary[$cell->getCalculatedValue()]
);
}
}
}
}
}
}
return $template;
}
After some debugging I found out that the text actually is replaced and that the service works like it should. The problem is that when I return the new PHPExcel file as a response to download, the excel is empty.
This is the code I use to return the file.
// create the writer
$writer = $this->get('phpexcel')->createWriter($mappedTemplate, 'Excel5');
// create the response
$response = $this->get('phpexcel')->createStreamedResponse($writer);
// adding headers
$dispositionHeader = $response->headers->makeDisposition(
ResponseHeaderBag::DISPOSITION_ATTACHMENT,
$file_name
);
$response->headers->set('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
$response->headers->set('Pragma', 'public');
$response->headers->set('Cache-Control', 'maxage=1');
$response->headers->set('Content-Disposition', $dispositionHeader);
return $response;
What am I missing?
Your code is missing the calls to the writer.
You only create the writer, but never use it, at least not in your shared code examples:
$objWriter = new PHPExcel_Writer_Excel2007($objPHPExcel);
$response = $this->get('phpexcel')->createStreamedResponse($objWriter)
Another thing is the content type: Do you have the apache content types setup correctly?
$response->headers->set('Content-Type', 'application/vnd.ms-excel; charset=utf-8');

Instagram Real Time Subscription Activity log

Working on instgram Real Time subscription. I am trying to save the image link based on Object id return from subscription. The activity log captures "N" only, not the image link. What I am doing wrong.
<?php
if (isset ($_GET['hub_challenge'])){
echo $_GET['hub_challenge'];
}
else{
$myString = file_get_contents('php://input');
$sub_update = json_decode($myString);
$access_token = 'xxxxx';
foreach($sub_update as $k => $v) // can be multiple updates per call
{ $objid = $v->object_id;
$recent_data = file_get_contents('https://api.instagram.com/v1/tags/'.$objid.'/media/recent?access_token='.$access_token);
$results=$results['data'];
$image_link = $results['images']['standard_resolution']['url'];
file_put_contents('activity.log', serialize($image_link), FILE_APPEND | LOCK_EX);
}
}
?>

PHP variables not showing up. GETid not working properly

I have all the login scripts and profiles set up. I have a data table where all the profile information is stored called plus_signup but I can't seem to get this GET[id] thing to work. Am I missing something? Here's what I have.
When I view the page with the code I have now, there are blank areas where PHP is supposed to fill in the variables.
session_start();
include "include/z_db.php";
if ($_GET['id']){
$id = $_GET['id'];
} else if (isset($_SESSION['id'])) {
$id = $_SESSION['id'];
}
else {
print "important data to render this page is missing";
exit();
$sql = mysql_query("SELECT * FROM plus_signup WHERE id='$userid'");
while($row = mysql_fetch_array($sql)){
$userid = $row["userid"];
$name = $row["name"];
$location = $row["location"];
$sex = $row["sex"];
$aboutme = $row["aboutme"];
}
$check_pic = "users/$id/image01.jpg";
$default_pic = "users/0/image01.jpg";
if (file_exists($check_pic)){
$user_pic = "<img src=\"$check_pic\" width=\"175px\"/>";
} else {
$user_pic = "<img src=\"$default_pic\"/>";
}}
I know it's a little late and that you may have already figured out the answer to this question, but I was having the same issue and just figured it out.
Your SQL query is calling on a variable that has not been defined.
session_start();
include "include/z_db.php";
if ($_GET['id']){
$id = $_GET['id'];
} else if (isset($_SESSION['id'])) {
$id = $_SESSION['id'];
}
else {
print "important data to render this page is missing";
exit();
$sql = mysql_query("SELECT * FROM plus_signup WHERE id='$userid'");
while($row = mysql_fetch_array($sql)){
$userid = $row["userid"];
$name = $row["name"];
$location = $row["location"];
$sex = $row["sex"];
$aboutme = $row["aboutme"];
}
$check_pic = "users/$id/image01.jpg";
$default_pic = "users/0/image01.jpg";
if (file_exists($check_pic)){
$user_pic = "<img src=\"$check_pic\" width=\"175px\"/>";
} else {
$user_pic = "<img src=\"$default_pic\"/>";
}}
You are getting the 'id' from the url and storing it as $id. When you call your query, you are having it search for where ID = $userid when you really should be having it search for ID = $id.
Make sure that your variables are the same throughout!
^Hope that helps some people avoid an hour or two of frustration when trying to figure out why their function isn't working!

Resources