Add date to attachment in PHP mailer SMTP - php

I am trying to add the date to a file which is emailed using SMTP in php. What i need is to add the date to the file name sent in the email, without changing the file name on the server. So my code still looks for 'file.csv' but names it '(date)file.csv' in the email attachment.
$mail->addAttachment('file.csv');
I have already tried.
$today = date("Y-m-d");
$filename = 'file'.$today.'csv'
$mail->addAttachment('./'.$filename, 'file.csv', 'base64', 'text/csv');
--solution--
$today = date("Y-m-d");
$filename = "file.csv";
$filename2 = 'file'.$today.'csv';
$mail->addAttachment($filename, $filename2);

It's not quite a duplicate as you know how to set both names, but you've simply got your filenames the wrong way around. Try this:
$today = date("Y-m-d");
$filename = 'file'.$today.'csv'
$mail->addAttachment('./file.csv', $filename, 'base64', 'text/csv');
The docs on this method are here.

Related

load data local infile user provided VALUES

My project requires external CSV files to be uploaded to a database every week and required outputs are extracted whenever required. Currently am using the below to browse through a HTML form and upload to the table. It works fine!
if(isset($_POST['submit']))
{
$file = $_FILES['file']['tmp_name'];
$handle = fopen($file,"r");
while(($fileop = fgetcsv($handle,1000,",")) !==false)
{
$placement_name = $fileop[2];
$statistics_date = $fileop[0];
$impressions = $fileop[5];
$clicks = $fileop[6];
$sql = mysql_query("INSERT INTO 'table'(source,advertiser,campaign,placement_name,statistics_date,impressions,clicks) VALUES ('xxx','yyy','zzz','$placement_name','$statistics_date','$impressions',' $clicks')");}
But now, we might need to do this on a daily basis and automated (which we hope to do with scheduled cron jobs), so decision was to use LOAD DATA LOCAL INFILE. As you could see the values inserted for source, advertiser and campaign are custom ones. How could we use the LOAD DATA... instead of the browse function?

mysql query to excel

Community,
I am currently working on a report builder. The objective of the report builder is to send out an email with an excel document with weekly information coming from an sql table. It is activated when the first person logs in for the day on Monday. If Monday is a holiday, and no one logs in that day, a timestamp will not be made in the database. When the user logs in Tuesday, it looks at the last timestamp to see if one was placed for the previous day. if not, it will fire on tuesday.
The first step in this process looks like this...
$today = cal_to_jd(CAL_GREGORIAN,date("m"),date("d"),date("Y"));
$yesterday = date('Y-m-d', strtotime($date .' -1 day'));
$holiday = false;
if(jddayofweek($today,1) == 'Tuesday')
{
if(mysql_num_rows(mysql_query("select report_date from report_builder where report_date = '{$yesterday}'")) == 0)
{
$holiday = true;
}
}
if(jddayofweek($today,1) == 'Monday' || $holiday === true)
{
$today = mysql_query("select report_date from report_builder where report_date = CURDATE()");
if(mysql_num_rows($today) == 0)
{
$date = date('Y-m-d H:i:s',time()-(7*86400));
mysql_query("INSERT into report_builder (report_date) VALUES (CURDATE())");
//More code here
**The question for this particular post is as follows:
Is it possible to send the information to a csv file that does not actually open so the user can see, but instead be saved to a temporary file? Can this be done in a way where it doesn't send the background html?**
Once this is accomplished, I wanted to send the file to a user using my current code that looks like this...
require("class.phpmailer.php");
$mail = new PHPMailer();
$mail->From = "**********";
$mail->AddAddress("*************");
$mail->Subject = "Test";
$mail->Body = "HI";
$fileName = $_FILES['file']['name'];
$tmpName = $_FILES['file']['tmp_name'];
$fileName = addslashes($fileName);
echo $fileName;
$mail->AddAttachment("temporary file path");
if(!$mail->Send())
{
echo 'Message was not sent.';
echo 'Mailer error:'.$mail->ErrorInfo;
}
Yes you can certainly write a files to disk and save it in any number of ways. I will however point you to something that might be a quick way to save some steps (i.e. not have to create a file in PHP) if you application server and your MySQL are on the same physical host. This is of course assuming that a CSV file would be suitable (i.e. you don't actually need to use a PHP Excel library to build an XLS or XLSX file)
SELECT [fields] INTO OUTFILE '/path/to/file'
FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"'
LINES TERMINATED BY '\n'
FROM your_table;
This will directly create a CSV at location path/to/file on the machine which can then be sent via PHP. Please note that the file name must not be an existing file name as this approach will not allow you to overwrite an existing file.
If your MySQL host is remote or you need to manipualte the data before writing to file, I would suggest looking at fputcsv() (http://php.net/manual/en/function.fputcsv.php) in order to write the data from your query directly to a file in CSV format.
$file = fopen('/path/to/file.csv', 'w');
while ($row = [YOUR DATABASE FETCH HERE]) {
fputcsv($file, $row);
}

How do you rename a textfile with a datetime stamp in php?

I'm new to php and programming in general, so forgive my ignorance on this one. I am trying to rename a textfile I created with a datetime stamp, and can't seem to get it right. I am writing info to a textfile after someone submits data, and that works, but I need to make every text file unique, so I need a unique naming convention. I even tried using the first name of the entry, but I can't get that to work either. Here's what I have so far:
<?php
$FirstName = $_POST["fname"].PHP_EOL;
$LastName = $_POST["lname"].PHP_EOL;
$Address = $_POST["address"].PHP_EOL;
$City = $_POST["city"].PHP_EOL;
$State = $_POST["st"].PHP_EOL;
$Zip = $_POST["zip"].PHP_EOL;
$Tel = $_POST["tel"].PHP_EOL;
$AddressFile = "Address_Entries.txt";
$ourFileHandle = fopen($AddressFile, "a") or die("can't open file");
$date = new DateTime();
echo $date->format('Y-m-d H:i:sP') . "\n";
fwrite($ourFileHandle, $FirstName);
fwrite($ourFileHandle, $LastName);
fwrite($ourFileHandle, $Address);
fwrite($ourFileHandle, $City);
fwrite($ourFileHandle, $State);
fwrite($ourFileHandle, $Zip);
fwrite($ourFileHandle, $Tel);
fclose($ourFileHandle);
echo "<p>File has been writtten to successfully!</p>";
rename("C:/xampp/security/htdocs/testes/Address_Entries.txt", $FirstName);
?>
Any help is appreciated. Thanks!
A
If you need a unique ID to name files with, try uniqid()
In windows you must use correct path:
rename("C:\\xampp\\security\\htdocs\\testes\\Address_Entries.txt", "C:\\xampp\\security\\htdocs\\testes\\$FirstName.txt");
This will rename the file using the timestamp. But a unique naming convention, this has a great chance to be unique, but is NOT unique. If someone was to post at the very same time... with the same first name... you'll have duplicate files.
Now is it a big chance? No.
<?php
$file = '/tmp/this-is-temp-file.txt';
$firstName = 'BeepBeep';
$timestamp = time();
rename($file, '/path/to/new/file/'.$firstName.'-'.$timestamp.'.txt');
?>
Possibly try to incorporate a uniqid() function. I don't think it is unique again as it uses time() (I think)... but may be better off padding it with a unique counter (like an ID from the database)
This assumes:
a) You have access to the FULL PATH
b) PHP has access to the file! You might be able to WRITE the file, but maybe not enough permissions to move, delete, rename, edit..

email attachment in php

$pieces = explode(",", $sentto);
for($i=0;$i<count($pieces)-1;$i++)
{
$fileatt = $_FILES['attachcopy']['tmp_name'];
$fileatt_type = $_FILES['attachcopy']['type'];
$fileatt_name = $_FILES['attachcopy']['name'];
$pieces[$i]=$pieces[$i].",";
$sel="insert into newmessage set sendto='".$pieces[$i]."',
sendfrom='".$almemailid."',
subject='".$subject."',
message='".$color."',
attachment='".$fileatt_name."',
updateddate = now()";
$selqur=mysql_query($sel) or die("Error (" . mysql_errno() .")" . mysql_error());
$lastid_id = mysql_insert_id();
$folderpath = "Attachment/".$lastid_id."".$fileatt_name;
move_uploaded_file($_FILES["attachcopy"]["tmp_name"],$folderpath);
}
Above program runs well in single emailid and send to attachment,
i have send more emailid with attachment there only send emil to all person and attachmnet
send only first emailid not for other.
i have store all attachment in foldr and attachment files are concodinate with auto increment id.
in the above for loop first time only stored attachment in folder next iteration not
stored in folder
You move the uploaded file from its temporary location (usually in /tmp) to $folderpath. The second time you try to do this, it's no longer going to be in its temporary location, because you already moved it. You need to do that outside of the loop or check if it's already in its new location.

PHP MYSQL FPDF retrieving pdf string stored as blob

Using the above technologies, I want to create a PDF, store it in my db, and email it. All with the click of one button.
I also want to call it up and have it be able to display with a hyperlink.
I am very new to FPDF. Therefore, I am trying to start off very slowly.
I began with this link stackoverflow Q
I put both parts of his code into the same page and tried with separate pages. I made the suggested changes/additions and even did a line by line comparison.
I still get the message, "format error: not a PDF or corrupted"
If I just $pdf->Output(); I get the pdf to display. It's either the way the string is being Output, or it's the header() function. It's not the storage method, unless my column setup is incorrect. BUt a blob is a blob, right?
If you want, I can upload the sanitized code. Just let me know what would help answer this.
Thanks
JJ
here's the code on request
here's where I enter it in:
<?php
session_start();
include "server.php";//my file to connect to db
require('fpdf.php');
$pdf=new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','B',16);
$pdf->Cell(40,10,'Hello World!');
$content = $pdf->Output("", "S"); //return the pdf file content as string
$sql = "update table set table_pdf= '".addslashes($content)."' " .
"where table_id = '188'";
mysql_query($sql);
//here's where I retrieve it
$sql2 = "select table_pdf from table where table_id = '188'";
$result2 = mysql_query($sql2);
$rs = mysql_fetch_assoc($result2);
$content2 = $rs['rdngs_hdr_pdf'];
header('Content-Type: application/pdf');
header("Content-Length: ".strlen(content2));
header('Content-Disposition: attachment; filename=myfile.pdf');
print $content2;
?>
Like I said, I have tried the other ideas on the other question link above. right now it just sits on the version where the addslashes is there.
Thanks for any help.
Give this a try. Instead of using the addslashes to escape the content, try using unpack to get it in a binary represenation:
$content = $pdf->Output("", "S"); //return the pdf file content as string
$data = unpack("H*hex", $content);
$sql = "update table set table_pdf= " . 0x".$data['hex']." . " " .
"where table_id = '188'";
For retrieving the data you should be able to just do a select, and then output the content, just like you are already doing.

Categories