Renaming Files after a move - php

I'm trying to rename a file while it is being moved into an "old" folder using a .cmd file and a .php file. This file is being e-mailed in a batch job and then moved into the old folder with the previous month and current year at the end of the report. Right now: The files are being e-mail correctly, and moved into the old folder, however the file name is not being renamed when it enters the "old" folder. Can anyone make any suggestions to my code? I can't seem to find out where the error is. Thanks
My code for .CMD file:
REM Email the 2 monthly stats files regarding gtwinapps
REM The report is sent at 9:20 AM every first monday of every month
REM in C:\Smurf_Reports\gtwinapps\Monthly_Stats
"c:\Program Files\xampp\php\php.exe" d:\batch\monthly_smurfreport_gtwinapps.php
move C:\Smurf_Reports\gtwinapps\Monthly_Stats\gtwinapps_statsmonthly.csv C:\Smurf_Reports\gtwinapps\Monthly_Stats\old
My code for .PHP file:
/*This application pickups up *.csv files from Monthly_Stats folder and then sends email to ops Support at ops.support#scotiabank.com.
The command file associated with this php file moves the .csv file into the "OLD" folder in the same directory
*/
$dirpath = "C:/Smurf_Reports/gtwinapps/Monthly_Stats/";
/* Renaming the batch job file to display the previous month and year once it is moved into the "OLD" folder for clarity purposes */
rename ("C:\Smurf_Reports\gtwinsapps\Monthly_Stats\gtwinapps_statsmonthly.csv", "C:\Smurf_Reports\ gtwinapps\Monthly_Stats\old\monthly_gtwinapps_" . date("F_Y", strtotime("-1 month")) . ".csv");
rename ("C:\Smurf_Reports\gtwinsapps\Monthly_Stats\monthly.csv", "C:\Smurf_Reports\gtwinapps\Month ly_Stats\old\gtwinapps_statsmonthly_" . date("F_Y", strtotime("-1 month")) . ".csv");
if ($handle = opendir($dirpath ))
{
$semi_rand = md5(time());
$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";
$headers .= "\nMIME-Version: 1.0\n" .
"Content-Type: multipart/mixed;\n" .
" boundary=\"{$mime_boundary}\"";
$email_message = "This is a multi-part message in MIME format.\n\n" .
"--{$mime_boundary}\n" .
"Content-Type:text/html; charset=\"iso-8859-1\"\n" .
"Content-Transfer-Encoding: 8bit\n\n" .
$message_text . "\n\n";
$email_message .= "--{$mime_boundary}\n";
/* This is the correct way to loop over the directory. */
while (false !== ($entry = readdir($handle)))
{
if (strpos($entry, '.csv',1))
{
$filepath = "";
$filesize = 0;
$filepath = $dirpath."".$entry;
$filesize = filesize ($filepath);
if (file_exists($filepath) && $filesize > 1)
{
$fileatt = $filepath;
$fileatt_name = $entry;
$fileatt_type = "application/octet-stream";
$message_text .= "<P>Hi</P>";
$file = fopen($fileatt,'rb');
$data = fread($file,filesize($fileatt));
fclose($file);
$data = chunk_split(base64_encode($data));
$email_message .= "Content-Type: {$fileatt_type};\n" .
" name=\"{$fileatt_name}\"\n" .
"Content-Disposition: attachment;\n" .
//" filename=\"{$fileatt_name}\"\n" .
"Content-Transfer-Encoding: base64\n\n" .
$data . "\n\n";
$email_message .= "--{$mime_boundary}\n";
}
$email_from = "ops.support#yahoo.com";
// $email_to = "ops.support#yahoo.com";
$email_to = "k.j#yahoo.com,g.h#yahoo.com";
$lastMonth = date('F-Y',strtotime('last month'));
$email_subject = "($lastMonth) Monthly Smurf Report for GTWINAPPS.";
$headers .= "From: ".$email_from."\r\n";
echo $filepath."</br>";
}
}
closedir($handle);
$ok = #mail($email_to, $email_subject, $email_message, $headers);
}

In your rename function, you need to either (A) escape your backslashes (\\), or (B) use forward slashes for directory separators

Related

how to attach multiple files from form to mail in php?

I am trying to attach two files at maximum, to send them by mail, but the files are sent by mail as binary code, so when I open the received mail I found the files as binary, here is my code:
$files = array();
if(is_uploaded_file($_FILES['cv']['tmp_name']))
array_push($files, $_FILES['cv']);
if(is_uploaded_file($_FILES['portfolio']['tmp_name']))
array_push($files, $_FILES['portfolio']);
$subject = "Contact Mail";
$headers = 'From: '.$email_fromto."\r\n".
"subject: {$subject}";
$randomVal = md5(time());
$mimeBoundary = "==Multipart_Boundary_x{$randomVal}x";
$headers .= "\nMIME-Version: 1.0\n";
$headers .= "Content-Type: multipart/mixed;\n" ;
$headers .= " boundary=\"{$mimeBoundary}\"";
$message = "This is a multi-part message in MIME format.\n\n" .
"--{$mimeBoundary}\n" .
"Content-Type: text/plain; charset=\"iso-8859-1\"\n" .
"Content-Transfer-Encoding: 7bit\n\n" .
"From: $sex $fname $lname.\r\n".
"Message: {$message}";
$email_fromto = "mail#mail.com";
foreach($files as $userfile){
$tmpName = $userfile['tmp_name'];
$fileType = $userfile['type'];
$fileName = $userfile['name'];
if(file($tmpName)){
$file = fopen($tmpName,'rb');
$data = fread($file,filesize($tmpName));
fclose($file);
$data = chunk_split(base64_encode($data));
$message .= "--{$mimeBoundary}\n" .
"Content-Type: {$fileType};\n" .
" name=\"{$fileName}\"\n" .
"Content-Transfer-Encoding: base64\n\n" .
$data . "\n\n" .
"--{$mimeBoundary}--\n";
}
}
so where is the error in what I did?
use like this
// generate a random string to be used as the boundary marker
$mime_boundary="==Multipart_Boundary_x".md5(mt_rand())."x";
// now we'll build the message headers
$headers = "From: $from\r\n" .
"MIME-Version: 1.0\r\n" .
"Content-Type: multipart/mixed;\r\n" .
" boundary=\"{$mime_boundary}\"";
// here, we'll start the message body.
// this is the text that will be displayed
// in the e-mail
$message="This is an example"
foreach($_FILES as $userfile){
// store the file information to variables for easier access
$tmp_name = $userfile['tmp_name'];
$type = $userfile['type'];
$name = $userfile['name'];
$size = $userfile['size'];
// if the upload succeded, the file will exist
if (file_exists($tmp_name)){
// check to make sure that it is an uploaded file and not a system file
if(is_uploaded_file($tmp_name)){
// open the file for a binary read
$file = fopen($tmp_name,'rb');
// read the file content into a variable
$data = fread($file,filesize($tmp_name));
// close the file
fclose($file);
// now we encode it and split it into acceptable length lines
$data = chunk_split(base64_encode($data));
}
}
// now we'll insert a boundary to indicate we're starting the attachment
// we have to specify the content type, file name, and disposition as
// an attachment, then add the file content.
// NOTE: we don't set another boundary to indicate that the end of the
// file has been reached here. we only want one boundary between each file
// we'll add the final one after the loop finishes.
$message .= "--{$mime_boundary}\n" .
"Content-Type: {$type};\n" .
" name=\"{$name}\"\n" .
"Content-Disposition: attachment;\n" .
" filename=\"{$fileatt_name}\"\n" .
"Content-Transfer-Encoding: base64\n\n" .
$data . "\n\n";
}
// here's our closing mime boundary that indicates the last of the message
$message.="--{$mime_boundary}--\n";
// now we just send the message
if (#mail($to, $subject, $message, $headers))
echo "Mail was Send Sucessfully";
else
echo "Failed to send";

mail attachment issue - why do i dont get the file properly?

i try to create a form with a option to upload files and to get it to my email .
for example that a user can put his info in the input fields and to add a file and when the user submit it i will get it all to my mail.
this is my code :
<?php
if(isset($_FILES) && (bool) $_FILES) {
$allowedExtensions = array("pdf","doc","docx","gif","jpeg","jpg","png","rtf","txt");
$files = array();
foreach($_FILES as $name=>$file) {
$file_name = $file['name'];
$temp_name = $file['tmp_name'];
$file_type = $file['type'];
$path_parts = pathinfo($file_name);
$ext = $path_parts['extension'];
if(!in_array($ext,$allowedExtensions)) {
die("File $file_name has the extensions $ext which is not allowed");
}
array_push($files,$temp_name);
}
// email fields: to, from, subject, and so on
$to = "dorozenman#gmail.com";
$from = $_POST['sender_email'];
$subject ="test attachment";
$message = "here ya go";
$headers = "From: $from";
// boundary
$semi_rand = md5(time());
$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";
// headers for attachment
$headers .= "\nMIME-Version: 1.0\n" . "Content-Type: multipart/mixed;\n" . " boundary=\"{$mime_boundary}\"";
// multipart boundary
$message = "This is a multi-part message in MIME format.\n\n" . "--{$mime_boundary}\n" . "Content-Type: text/plain; charset=\"iso-8859-1\"\n" . "Content-Transfer-Encoding: 7bit\n\n" . $message . "\n\n";
$message .= "--{$mime_boundary}\n";
// preparing attachments
for($x=0;$x<count($files);$x++){
$file = fopen($files[$x],"rb");
$data = fread($file,filesize($files[$x]));
fclose($file);
$data = chunk_split(base64_encode($data));
$message .= "Content-Type: {\"application/octet-stream\"};\n" . " name=\"$files[$x]\"\n" .
"Content-Disposition: attachment;\n" . " filename=\"$files[$x]\"\n" .
"Content-Transfer-Encoding: base64\n\n" . $data . "\n\n";
$message .= "--{$mime_boundary}\n";
}
// send
$ok = #mail($to, $subject, $message, $headers);
if ($ok) {
echo "<p>mail sent to $to!</p>";
} else {
echo "<p>mail could not be sent!</p>";
}
}
?>
(and file arrive named... tmp/phpcVjk4w/ ) any suggestions?
Change:
array_push($files,$temp_name);
to:
array_push($files, array('temp_name' => $temp_name, 'file_name' => $file_name));
And change:
// preparing attachments
for($x=0;$x<count($files);$x++){
$file = fopen($files[$x],"rb");
$data = fread($file,filesize($files[$x]));
fclose($file);
$data = chunk_split(base64_encode($data));
$message .= "Content-Type: {\"application/octet-stream\"};\n" . " name=\"$files[$x]\"\n" .
"Content-Disposition: attachment;\n" . " filename=\"$files[$x]\"\n" .
"Content-Transfer-Encoding: base64\n\n" . $data . "\n\n";
$message .= "--{$mime_boundary}\n";
}
To:
// preparing attachments
for($x=0;$x<count($files);$x++){
$temp_name = $files[$x]['temp_name']; // temporary file location
$file_name = $files[$x]['file_name']; // filename
$file = fopen($temp_name,"rb");
$data = fread($file,filesize($temp_name));
fclose($file);
$data = chunk_split(base64_encode($data));
$message .= "Content-Type: {\"application/octet-stream\"};\n" . " name=\"$file_name\"\n" .
"Content-Disposition: attachment;\n" . " filename=\"$file_name\"\n" .
"Content-Transfer-Encoding: base64\n\n" . $data . "\n\n";
$message .= "--{$mime_boundary}\n";
}
The difference here is pulling the filename into the $files array along with the temporary file location. You need both, where is the file on the server, and what is the name of the file when uploaded.
Which is absolutely normal.
Basically, files are uploaded to your server, PHP temporary stores them in /tmp/ directory.
$files = array();
foreach($_FILES as $name=>$file) {
$temp_name = $file['tmp_name'];
array_push($files,$temp_name);
}
Above, you put that temporary name into an array, and below you put that name in your mail :
for($x=0;$x<count($files);$x++){
$message .= name=\"$files[$x]\"; //...
}
What do you want your script to do?

How to rename files in FTP Move Command in PHP

I'm trying to move a file after a batch job e-mail has been sent into the "OLD" folder.
I have successfully determined the code to do so. Right now the file is called monthly_mssql, I'm trying to rename the file to monthly_mssql_mmmyyyy.
With the month and year added to the end of the file I can keep track of determining which reports are for which month. How would I edit the existing command file?
MY CODE FOR CMD FILE:
REM The report is generated automatically and must be sent at 9:50 AM of the first Monday of every month, file is located
REM in C:\Reports\mssql\Monthly_Stats
"C:\Program Files\xampp\php\php.exe" "c:\htdocs\MultipleReport\monthly_smurfreport_email.php"
move C:\Smurf_Reports\mssql\Monthly_Stats\monthly_mssql.csv C:\Smurf_Reports\mssql\Monthly_Stats\old
MY CODE FOR PHP FILE:
$dirpath = "C:/Reports/mssql/Monthly_Stats/";
if ($handle = opendir($dirpath ))
{
$semi_rand = md5(time());
$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";
$headers .= "\nMIME-Version: 1.0\n" .
"Content-Type: multipart/mixed;\n" .
" boundary=\"{$mime_boundary}\"";
$email_message = "This is a multi-part message in MIME format.\n\n" .
"--{$mime_boundary}\n" .
"Content-Type:text/html; charset=\"iso-8859-1\"\n" .
"Content-Transfer-Encoding: 8bit\n\n" .
$message_text . "\n\n";
$email_message .= "--{$mime_boundary}\n";
/* This is the correct way to loop over the directory. */
while (false !== ($entry = readdir($handle)))
{
if (strpos($entry, '.csv',1))
{
$filepath = "";
$filesize = 0;
$filepath = $dirpath."".$entry;
$filesize = filesize ($filepath);
if (file_exists($filepath) && $filesize > 1)
{
$fileatt = $filepath;
$fileatt_name = $entry;
$fileatt_type = "application/octet-stream";
$message_text .= "<P>Hi</P>";
$file = fopen($fileatt,'rb');
$data = fread($file,filesize($fileatt));
fclose($file);
$data = chunk_split(base64_encode($data));
$email_message .= "Content-Type: {$fileatt_type};\n" .
" name=\"{$fileatt_name}\"\n" .
"Content-Disposition: attachment;\n" .
//" filename=\"{$fileatt_name}\"\n" .
"Content-Transfer-Encoding: base64\n\n" .
$data . "\n\n";
$email_message .= "--{$mime_boundary}\n";
}
$email_from = "k.j#yahoo.com";
// $email_to = "k.j#yahoo.com";
$email_to = "k.j#yahoo.com";
$lastMonth = date('F-Y',strtotime('last month'));
$email_subject = "($lastMonth) Report for MS-SQL.";
$headers .= "From: ".$email_from."\r\n";
echo $filepath."</br>";
}
}
closedir($handle);
$ok = #mail($email_to, $email_subject, $email_message, $headers);
}
/*if (file_exists($filename) && $size > 228 && $EmailAdd <> "")
{
$fileatt = $filename;
$fileatt_name = $groupname.".csv";
if ($uemail <> "")
$email_from = $uemail;
else
$email_from = $username."#yahoo.com";
$email_to = $email_from;
$email_subject = " Messages for Priority '".$p."' - ".$groupname." - ".$displaydate;
$headers .= "From: ".$email_from. "\r\n";
$headers .= "Cc: ".$EmailAdd. "\r\n";
$headers .= "Bcc: k.j#yahoo.com";
$email_message .= "<P>Hi</P>";
$email_message .= "<P><B>Please find attached Monthly Smurf Report Stats."</U></B>\n";
$email_message .= "<P><P>Thanks,<P>;
set_error_handler("myErrorHandler");
$ok = #mail($email_to, $email_subject, $email_message, $headers);
if ($ok)
{
unlink($filename);
}
else
{
$file = "C:/Reports/Operation/Daily_Stats/smtperrlog.txt";
$fh = fopen($file, 'r+');
$contents = fread($fh, filesize($file));
fclose($fh);
$stderr = fopen ('C:/Reports/Operation/Daily_Stats/smtperrlog.txt', 'w+');
fwrite($stderr,"");
fclose($stderr);
$email_fromerr = "k.j#yahoo.com";
$email_toerr = "k.j#yahoo.com";
$email_subjecterr = "Monthly Stats";
$email_messageerr = $contents;
$headerserr .= "From: ".$email_fromerr. "\r\n";
#mail($email_toerr, $email_subjecterr, $email_messageerr, $headerserr);
}
}
*/
$message_text = "";
$p = "";
$EmailAdd = "";
$headers = "";
$counter = 0;
In my opinion, moving it with a batch file would be unnecessary. I would move it directly in PHP with the rename() method. You can append a date at the end of the file with date().
An example of this would be:
rename("C:\Smurf_Reports\mssql\Monthly_Stats\monthly_mssql.csv", "C:\Smurf_Reports\mssql\Monthly_Stats\old\monthly_mssql_" . date("m_Y") . ".csv");
Edit
$cMonth = intval(date("m")); //Retrieves current month, converts to int value
$lastMonth = ($cMonth == 1 ? "12" : $cMonth - 1); //If it's January, let's set the month to December
$cYear = ($cMonth == 1 ? intval(date("Y")) - 1 : date("Y")); //If it's January, let's also set the year back by one so the dates match up
rename("C:\Smurf_Reports\mssql\Monthly_Stats\monthly_mssql.csv", "C:\Smurf_Reports\mssql\Monthly_Stats\old\monthly_mssql_" . $lastMonth . "_" . $cYear . ".csv");

PHP Mail xlsx-file created with PHPExcel as attachment

So I'm trying to generate and save an Excel-file to the server. This works flawlessly with PHPExcel. The next step is to read the file, e-mail it as an attachment and then delete it.
For some reason, PHP does not recognize xlsx as a proper file:
/* excel is generated before here */
$filename = "/results/excel/export-" . $today . ".xlsx";
$writer = new PHPExcel_Writer_Excel2007($exc);
$writer->save($filename);
/* so far so good; the file is created and exists on the server */
$to = "someone#domain.com";
$sendermail = "no-reply#domain.com";
$from = "Sender <" . $sendermail . ">";
$subject = "Email with attachment";
$message = "Here you go";
$file = $filename;
$semi_rand = md5(time());
$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";
$headers = "From: $from";
$headers .= "\nMIME-Version: 1.0\n" . "Content-Type: multipart/mixed;\n" . " boundary=\" {$mime_boundary}\"";
$message = "--{$mime_boundary}\n" . "Content-Type: text/plain; charset=\"iso-8859-1\"\n" .
"Content-Transfer-Encoding: 7bit\n\n" . $message . "\n\n";
if(is_file($file)) {
$message .= "--{$mime_boundary}\n";
$fp = #fopen($file, "rb");
$data = #fread($fp, filesize($file));
#fclose($fp);
$data = chunk_split(base64_encode($data));
$message .= "Content-Type: application/octet-stream; name=\"" . basename($file). ";\n" . "Content-Transfer-Encoding: base64\n\n" . $data . "\n\n";
$message .= "--{$mime_boundary}--";
$returnpath = "-f" . $sendermail;
mail($to, $subject, $message, $headers, $returnpath);
} else {
echo("This is not a file: " . $file);
}
Which always gives me "This is not a file...". How do I read the XLSX-file?
here's a tip to prompt the excel and also send the file as an attachment without saving the file on server:
$objWriter = PHPExcel_IOFactory::createWriter ($objPHPExcel, 'Excel2007');
$objWriter->save('php://output');
$data = ob_get_contents();
$sendmail=new ExcelMail($data); //this is your mail class; if you use zend mail use addattachement($data); and Zend_Mime
The outputted message means is_file() is failing . This can happen for a number of reasons, but as far as I know not because the file format. As such, I would recommend looking into the following things:
Is the file actually there? You say you have the file saved, but you have to make sure it actually is.
Is the file path the xslx file is using correct?
Is the file path to the xslx file to the actual xml file and not to a symlink to it?
Are the permissions of the xslx file set so that the php script is allowed to acces them?
I believe it has to be one of those problems...
Okay, I found out what it was. $filename was actually a direct (http://...) link to the file, not a relative link. Changed it to be relative and it worked :).

php mail attachments weird behaviour

I need some help here with a really weird situation.. i made a webmail form to send emails with multiple attachments, it worked out of the box yesterday but today it only sends 1 file as an attachment and not multiple. O_O
I revert my SVN to an older revision also and the problem still persists, any idea? this is really weird.. how working stuff brake from one day to another, i think the problem must be the SMTP server or something. Help please!
Code:
$semi_rand = md5(time());
$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";
$attachments = TRUE;
$body = "This is a multi-part message in MIME format.\n\n" .
"--{$mime_boundary}\n" .
"Content-Type: text/plain; charset=iso-8859-1\n" .
"Content-Transfer-Encoding: 7bit\n\n" .
$body . "\n\n";
$body .= "--{$mime_boundary}\n";
$attach = array();
for($i=0; $i<count($_FILES['file']['name']);$i++)
{
$tmp_name = $_FILES['file']['tmp_name'][$i];
$type = $_FILES['file']['type'][$i];
$name = $_FILES['file']['name'][$i];
$size = $_FILES['file']['size'][$i];
if (file_exists($tmp_name)){
$kb = $size/1024;
$kbSize = round($kb*100)/100;
if(is_uploaded_file($tmp_name)){
$file = fopen($tmp_name,'rb');
$fdata = fread($file,filesize($tmp_name)); //stream file to var and send it in headers
fclose($file);
$fdata = chunk_split(base64_encode($fdata));
$body .= "Content-Type: {\"application/octet-stream\"};\n" . " name=\"$name\"\n" .
"Content-Disposition: attachment;\n" . " filename=\"$name\"\n" .
"Content-Transfer-Encoding: base64\n\n" . $fdata . "\n\n";
$body .= "--{$mime_boundary}-\n";
}
}
}
$sent = myMailer::sendAttached($from,$to,$subject,$body,$mime_boundary,$multi);
MyMailer class, sendAttached Method:
public static function sendAttached($from,$to,$subject,$body,$mime,$multi=FALSE)
{
$headers = 'From: Website <'.$from.'>'. "\r\n".
'Reply-To: '.$from. "\r\n".
"MIME-Version: 1.0\r\n" .
"Content-Type: multipart/mixed;\r\n" .
" boundary=\"{$mime}\"";
if($multi == TRUE && is_array($to)){
foreach($to as $item)
{
mail(trim($item),$subject,$body,$headers);
}
return TRUE;
}else{
return mail($to,$subject,$body,$headers);
}
}
Did you perhaps at some point move theo following outside the for loop:
$semi_rand = md5(time());
$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";
Ive never tried to create a complex multipart message from scratch like this (i always use an existing library like Swift Mailer or Zend_Mail), but doesnt each file have to be its own part and thus have its own boundries?

Categories