Open and attach file to mailer from database string [duplicate] - php

So:
// Setup mail class, recipients and body
$mailer->AddAttachment('/home/mywebsite/public_html/file.zip', 'file.zip');
The AddAttachment function has four arguments:
AddAttachment(PATH_TO_FILE, FILENAME, ENCODING, HEADER_TYPE)
I used to use xmail() and when I added a attachment here, I passed the filename and the content, that should be in it.
Like this:
$xmail->addAttachment('myamazingfile.pdf', $content);
How can I make it work the same way, so when i call AddAttachment() from the PHPmailer class, I can either pass the same or something like it, so I dont need to have a actual file on my server to send?

AddStringAttachment($string,$filename,$encoding,$type)
eg
$mail = new PHPMailer();
$mail->AddStringAttachment($string,$filename,$encoding,$type);
https://phpmailer.github.io/PHPMailer/classes/PHPMailer-PHPMailer-PHPMailer.html#method_addStringAttachment

since that AddAttachment() function is expecting a path rather than byte data, you should do a php convert to temp file function and then pass that path string into your function
$prefix = 'ConvertMediaArgs_'.time().'_';
$tempfile = tempnam( $this->tempdir, $prefix );
// Args file create failure: kill script with TEMPFILEFAIL error
if($tempfile === false) {
die('file could not be created');
}
// Write args as Key=Val (\n) to file
$fullpath = $this->tempdir.$tempfile;
$content = $someContent // <---------------- this is your file's data
$handle = fopen( $tempfile, "w");
fwrite( $handle, $content );
// $fullpath is the path you wanna pass to your function
$xmail->addAttachment( $fullpath, $content );

Related

PHP. How to read a file, if it is writing without a problem with "a+", but is not readable with "r"?

I have two scripts: one of them writes the value of a variable to a file. In another script, I try to read it. It is written without problems, but it is not readable.
Here I write to a file:
$peer_id=2000000001;
$fileLocation = getenv("DOCUMENT_ROOT") . "/peer_id.txt";
$file = fopen($fileLocation,"a+");
fwrite($file, $peer_id);
fclose($file);
Here I read the file:
$fileLocation = getenv("DOCUMENT_ROOT") . "/peer_id.txt";
$file = fopen($fileLocation,"r");
if(file_exists($fileLocation)){
// Result is TRUE
}
if(is_readable ($file)){
// Result is FALSE
}
// an empty variables, because the file is not readable
$peer_id = fread($file);
$peer_id = fileread($file);
$peer_id = file_get_contents($file);
fclose($file);
The code runs on "sprinthost" hosting, if that makes a difference. There are suspicions that this is because of that hosting.
file_get_contents in short runs the fopen, fread, and fclose. You don't use a pointer with it. You should just use:
$peer_id = file_get_contents($fileLocation);
That is the same for is_readable:
if(is_readable($fileLocation)){
// Result is FALSE
}
So full code should be something like:
$fileLocation = getenv("DOCUMENT_ROOT") . "/peer_id.txt";
if(file_exists($fileLocation) && is_readable($fileLocation)) {
$peer_id = file_get_contents($fileLocation);
} else {
echo 'Error message about file being inaccessible here';
}
The file_get_contents has an inverse function for writing; https://www.php.net/manual/en/function.file-put-contents.php. Use that with the append constant and you should have the same functionality your first code block had:
file_put_contents($fileLocation, $peer_id, FILE_APPEND | LOCK_EX);

Error on PHP fgets() reading a line of CSV

I am working on this snippet. Why am I getting fgets() error on line 6?
Warning: fgets() expects parameter 1 to be resource, string given in
D:\wamp64\www\WP\wp-content\plugins\test.php on line 6
Code:
<?php
$file = "http://localhost:8080/WP/Data.csv";
function wdm_validate_csv($csv_file)
{
$requiredHeaders = array('title', 'price','color');
$firstLine = fgets($csv_file); //get first line of the CSV file
$fileHeader = str_getcsv(trim($firstLine), ',', "'"); //parse the contents to an array
//check the headers of the file
if ($foundHeaders !== $requiredHeaders) {
// report an error
return false;
}
return true;
}
wdm_validate_csv($file);
As you can see I have a CSV file at this $file = "http://localhost:8080/WP/Data.csv" directory and trying to read it
if you read a file with Url you can use the function file_get_contents(), but if you need to read in the local server change this http://localhost:8080/WP/Data.csv for "./WP/Data.csv" if the php file is in the root directory.
`
<?php
// Create a stream
$opts = array(
'http'=>array(
'method'=>"GET",
'header'=>"Accept-language: en\r\n" .
"Cookie: foo=bar\r\n"
)
);
$context = stream_context_create($opts);
// Open the file using the HTTP headers set above
$file = file_get_contents('http://www.example.com/', false, $context);
?>
`
Using file()[0] will give you the first line of a file.
file() returns a file as an array line by line, and [0] means give me the first line only.
Then I assume it's a typo $fileheaders and $foundheaders?
$file = "http://localhost:8080/WP/Data.csv";
function wdm_validate_csv($csv_file)
{
$requiredHeaders = array('title', 'price','color');
$firstLine = file($csv_file)[0]; //get first line of the CSV file
$fileHeader = str_getcsv(trim($firstLine), ',', "'"); //parse the contents to an array
//check the headers of the file
if ($fileHeader !== $requiredHeaders) {
// report an error
return false;
}
return true;
}
wdm_validate_csv($file);
Assuming you're going to do other stuff with the file after validating its headers, I think it makes sense to open it and pass the resource handle to the function instead of just the path.
$file = fopen("http://localhost:8080/WP/Data.csv");
$valid_headers = wdm_validate_csv($file);
If your CSV is valid, you can combine fgets and str_getcsv into one operation with fgetcsv.
function wdm_validate_csv($csv_file)
{
$requiredHeaders = array('title', 'price','color');
$fileHeader = fgetcsv($csv_file); //get first line of the CSV file
return $fileHeader == $requiredHeaders;
}
file_get_contents and file are great, but they're both going to read the entire file in, which is a bit heavy if you just need to check the first line.
As the error suggests, fgets requires a resource, not a string. Try using file_get_contents instead:
<?php
$file = "http://localhost:8080/WP/Data.csv";
function wdm_validate_csv($csv_file)
{
$requiredHeaders = array('title', 'price','color');
$firstLine = file_get_contents($csv_file); //get first line of the CSV file
$data = str_getcsv(trim($firstLine), ',', "'"); //parse the contents to an array
$foundHeaders = array_key_exists($data[0]) ? $data[0] : null;
//check the headers of the file
if ($foundHeaders !== $requiredHeaders) {
// report an error
return false;
}
return true;
}
wdm_validate_csv($file);

How to get the content of the file in variable in Laravel 5.5

I am uploading files that I need to attach to email via office365 API.
What I need is the content of the file in a variable WITHOUT storing/saving the file, how can I do that?
foreach ($request->filesToUpload as $file) {
$originalName = $file->getClientOriginalName();//working
$content = $file->getContent();//<- I need this, but not working
//$this->addAttachment($content, $originalName) //logic for later
}
Access the contents of the file like so:
$content = file_get_contents(Input::file('nameAttribute')->getRealPath());
or in other words inside that loop
$contents = file_get_contents($file->getRealPath());
Get the real path with object methods, and you may interact with it like any other file.
Waqas Bukhary,
You get that result, beucause, getContent is not a method of uploadedFiles, check the documentation.
But you have the path, so you can always read the content, like:
$path = $file->path();
$handle = fopen($path, 'r');
$content = fread($handle, filesize($path);
fclose($handle);
You can also use the Request File method if you know the name of the file field, check it here.

PHPMailer attachment, doing it without a physical file

So:
// Setup mail class, recipients and body
$mailer->AddAttachment('/home/mywebsite/public_html/file.zip', 'file.zip');
The AddAttachment function has four arguments:
AddAttachment(PATH_TO_FILE, FILENAME, ENCODING, HEADER_TYPE)
I used to use xmail() and when I added a attachment here, I passed the filename and the content, that should be in it.
Like this:
$xmail->addAttachment('myamazingfile.pdf', $content);
How can I make it work the same way, so when i call AddAttachment() from the PHPmailer class, I can either pass the same or something like it, so I dont need to have a actual file on my server to send?
AddStringAttachment($string,$filename,$encoding,$type)
eg
$mail = new PHPMailer();
$mail->AddStringAttachment($string,$filename,$encoding,$type);
https://phpmailer.github.io/PHPMailer/classes/PHPMailer-PHPMailer-PHPMailer.html#method_addStringAttachment
since that AddAttachment() function is expecting a path rather than byte data, you should do a php convert to temp file function and then pass that path string into your function
$prefix = 'ConvertMediaArgs_'.time().'_';
$tempfile = tempnam( $this->tempdir, $prefix );
// Args file create failure: kill script with TEMPFILEFAIL error
if($tempfile === false) {
die('file could not be created');
}
// Write args as Key=Val (\n) to file
$fullpath = $this->tempdir.$tempfile;
$content = $someContent // <---------------- this is your file's data
$handle = fopen( $tempfile, "w");
fwrite( $handle, $content );
// $fullpath is the path you wanna pass to your function
$xmail->addAttachment( $fullpath, $content );

CSV file_get_contents sending PHP

I'm trying to send a .CSV file with PHP. The file is written to disk before it's sent but when I try to attach the file with file_get_contents(); the structure of the .CSV isn't preseved yet when try and send the file that's created before it's sent I get a resource id (#183) so how can i attach a file which the user can open as a .CSV file? I've made sure the mime type and headers are correct
EDIT
if(!file_exists(_PS_ORDERS_DIR_.$orderDate.'/'.$file_name.'.csv'))
{
if($file = fopen (_PS_ORDERS_DIR_.$orderDate.'/'.$file_name.'.csv', 'x+'))
{
foreach ($list as $fields)
{
fputcsv($file, $fields);
}
$attachment['mime'] = 'application/vnd.ms-excel';
$attachment['content'] = file_get_contents(_PS_ORDERS_DIR_.$orderDate.'/'.$file_name.'.csv');
$attachment['name'] = $order.'order';
Mail::Send(1, 'order_conf', 'Order CSV Attachment', $success, 'dan.farr#gmail.com', CakeToppers, NULL, NULL, $attachment);
return true;
}
If you are using Swift Mailer, there is no need for file_get_contents(), you can just attach the file directly.
From the Swift Mailer documentation:
//Create the attachment
// * Note that you can technically leave the content-type parameter out
$attachment = Swift_Attachment::fromPath('/path/to/image.jpg', 'image/jpeg');
//Attach it to the message
$message->attach($attachment);
So for you that would be:
$attachment = Swift_Attachment::fromPath(_PS_ORDERS_DIR_.$orderDate.'/'.$file_name.'.csv', 'application/vnd.ms-excel');
//Attach it to the message
$message->attach($attachment);

Categories