A attachment file with a php form in wordpress - php

I am making a php form in wordpress.I would like to attach a notepad or PDF file along this form.I am getting all this in email using mail function in a body variable for example
$body =" Attachment: $Attachmentfile";
Instead of file i am receiving file name that user uploading instead of file.I am trying to receive file in email.Actually i am learning too that how to do it.
My php code for assigning to htm file tag is,
if(trim($_POST['Attachmentfile']) === '') {
$AttachmentfileError = 'Please enter a Pdf, Notepad or Word file.';
$hasError = true;
}
else
{
if($_FILES["Attachmentfile"]["name"] != "")
{
$strFilesName = $_FILES["Attachmentfile"]["name"];
$strContent = chunk_split(base64_encode(file_get_contents($_FILES["Attachmentfile"]["tmp_name"])));
$strHeader .= "--".$strSid."\n";
$strHeader .= "Content-Type: application/octet-stream; name=\"".$strFilesName."\"\n";
$strHeader .= "Content-Transfer-Encoding: base64\n";
$strHeader .= "Content-Disposition: attachment; filename=\"".$strFilesName."\"\n\n";
$strHeader .= $strContent."\n\n";
}
else
{
$Attachmentfile = trim($_POST['Attachmentfile']);
}
}
and my Html code for getting file ,
<li class="left">
<label for="CV">Attachments :</label><span class="error">*</span><br>
<input class="txt" type="file" name="Attachmentfile" id="Attachmentfile" value="<?php if(isset($_POST['Attachmentfile'])) echo $_POST['Attachmentfile'];?>">
</li>
and this is my mail function code,
$headers = 'From: '.$name.' <'.$emailTo.'>' . "\r\n" . 'Reply-To: ' . $email;
$headers .= "\r\n" . 'Content-type: text/html';
wp_mail($emailTo, $subject, $body, $headers);
$emailSent = true;
Can you help and modify my code in order to get file in email.Thanks friends.

function property_add() {
$data = $_POST['data'];
$data = array_map('trim',$data);
extract($data);
$to = "reciever mail here ";
$subject = "subject here";
$message ='Message here';
$attachments = array(); // initialize attachment array
$upload_dir = wp_upload_dir(); // look for this function in wordpress documentation at codex
$upload_dir = $upload_dir['path'];
foreach ($_FILES["images"]["error"] as $key => $error) {
if ($error == UPLOAD_ERR_OK) {
$tmp_name = $_FILES["images"]["tmp_name"][$key]; // Get temp name of uploaded file
$name = time().'_'.$_FILES["images"]["name"][$key]; // rename it to whatever
move_uploaded_file($tmp_name, "$upload_dir/$name"); // move file to new location
$attachments[] = "$upload_dir/$name"; // push the new uploaded file in attachment array
}
}
add_filter( 'wp_mail_content_type', 'set_html_content_type' ); // allow html tags in mail
if(wp_mail($to, $subject, $message,'',$attachments)) {
echo "any success message>";
} else {
echo "failure message ";
}
remove_filter( 'wp_mail_content_type', 'set_html_content_type' ); // remove filter to avoid conflicts
if(!empty($attachments)) {
foreach($attachments as $attachment) {
#unlink($attachment); // delete files after sending them
}
}
}
this is an extract of one of my project .. change it according to your needs i wrote comment so that you get better better ..
call this function on form submit

Related

Mail Server Spam Security Issue

I'm getting spam emails from my web form every week. I have tried to make some changes in my query, but that hasn't helped. I am sharing my query below, including the headers.
Can someone help me find where the problem is?
<?php
$submitted_email = '';
if (isset($_SESSION['form'][$mail_from_email])) {
$submitted_email = $_SESSION['form'][$mail_from_email];
}
if (check_email($submitted_email) && $send_from_users_email === false) {
$from = $reply_to = $_SESSION['form'][$mail_from_name].' <'.$submitted_email.'>';
} else {
$from = '<'.$email.'>';
$reply_to = check_email($submitted_email) ? '<'.$submitted_email.'>' : $from;
}
$subject = '';
if (isset($_SESSION['form'][$mail_subject])) {
$subject = $_SESSION['form'][$mail_subject];
}
//email headers
if ($windows_server === true) {
$headers = "From: test.co.uk\r\n" .
"Reply-to: test.co.uk\r\n" .
"Return-Path: test.co.uk\r\n".
"MIME-Version: 1.0\r\nContent-Type: multipart/mixed; " .
"boundary=$mixed_mime_boundary";
} else {
$headers = "From: $from\n" .
"Reply-to: $reply_to\n" .
"MIME-Version: 1.0\nContent-Type: multipart/mixed; " .
"boundary=$mixed_mime_boundary";
} else {
$headers = "From: $from\n" .
"Reply-to: $reply_to\n" .
"MIME-Version: 1.0\nContent-Type: multipart/mixed; " .
"boundary=$mixed_mime_boundary";
}
////////////////////////////
// CONSTRUCT HTML CONTENT //
////////////////////////////
//Construct HTML email content, looping through each form element
//Note: When you get to a file attachment you need to use $_FILES['form_element']['name']
//This will just output the name of the file. The files will actually be attached at the end of the message.
//Set a variable for the message content
$html_content = "<html>\n<head>\n<title>" .
safe_escape_string($subject) .
"</title>\n</head>\n<body>\n<p>\n";
////////////////////////////
// CONSTRUCT TEXT CONTENT //
////////////////////////////
//construct a plain text version of the email.
$text_content = '';
//build a message from the reply for both HTML and text in one loop.
foreach ($form_fields as $field => $label) {
$html_content .= '<b>' . safe_escape_string($label) . '</b> ';
$text_content .= "$label ";
if (isset($_FILES[$field])) {
$string = (isset($_FILES[$field]['name'])) ? $_FILES[$field]['name'] : '';
} else {
$string = (isset($_SESSION['form'][$field])) ? $_SESSION['form'][$field] : '';
}
$html_content .= nl2br(safe_escape_string($string)) . "<br /><br />\n";
$text_content .= "$string\n\n";
}
//close the HTML content.
$html_content .= "</p>\n</body>\n</html>";
/////////////////////////////
// CONSTRUCT EMAIL MESSAGE //
/////////////////////////////
//Now we combine both HTML and plain text version of the email into one.
//Creating the message body which contains a Plain text version and an HTML version,
//users email client will decide which version to display
$message = "\r\n--$mixed_mime_boundary\r\n" .
"Content-Type: multipart/alternative; boundary=$alt_mime_boundary\r\n\r\n" .
"--$alt_mime_boundary\r\n" .
"Content-Type: text/plain; charset=UTF-8; format=flowed\r\n" .
"Content-Transfer-Encoding: Quoted-printable\r\n\r\n" .
"$text_content\r\n\r\n" .
"--$alt_mime_boundary\r\n" .
"Content-Type: text/html; charset=UTF-8\r\n" .
"Content-Transfer-Encoding: Quoted-printable\r\n\r\n" .
"$html_content\r\n\r\n" .
"--$alt_mime_boundary--\r\n\r\n" .
"\r\n\r\n--$mixed_mime_boundary";
//////////////////////
// FILE ATTACHMENTS //
//////////////////////
//loop through the $_FILES global array and add each attachment to the form.
if (isset($_FILES)) {
foreach ($_FILES as $attachment) {
$filename = $attachment['name'];
//if the file has been uploaded
if ($attachment['error'] === UPLOAD_ERR_OK && is_uploaded_file($attachment['tmp_name'])) {
$file = fopen($attachment['tmp_name'],'rb');
$data = fread($file,filesize($attachment['tmp_name']));
fclose($file);
$data = chunk_split(base64_encode($data));
$message .= "\r\nContent-Type: application/octet-stream; name=\"$filename\"" .
"\r\nContent-Disposition: attachment; filename=\"$filename\"" .
"\r\nContent-Transfer-Encoding: base64\r\n\r\n$data\r\n\r\n--$mixed_mime_boundary";
} else if ($attachment['error'] !== UPLOAD_ERR_NO_FILE) {
//try to provide a useful error message determined from the error code.
switch ($attachment['error']) {
case UPLOAD_ERR_INI_SIZE:
case UPLOAD_ERR_FORM_SIZE:
$error = "File $filename exceeds the " . ini_get('upload_max_filesize') . 'B limit for the server.';
break;
case UPLOAD_ERR_PARTIAL:
$error = "Only part of the file $filename could be uploaded, please try again.";
break;
default:
$error = "There has been an error attaching the file $filename, please try again.";
}
redirect($return_url, $error);
}
}
}
//finish off message
$message .= '--';
//for windows users.
if ($windows_server === true) {
ini_set('sendmail_from', $email);
}
//if the mail sending works
if (#mail($email, $subject, $message, $headers)) {
//set the success message
$notice = $message_success;
unset($_SESSION['form']);
} else {
$notice = "I'm sorry, there seems to have been an error trying to send your email. Please try again.";
}
//redirect to the form
redirect($return_url, $notice);
}
?>

multiple files as attachment from a form and send a email

Following is the code I am using to send multiple files as attachment in a mail, tested it in local environment, the attachments were reaching the mail box but as empty files, and in live environment, result is mail could not be sent, though files get saved in the upload folder on the server...a newbie in php so please can anyone help what am I doing wrong..??
In local environment i was using this code $server_file = "/localhost:81/xyz/uploads/$path_parts[basename]"; in place what is mentioned down there under move this file to the server
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
//did files get sent
if(isset($_FILES) && (bool) $_FILES) {
//define allowed extensions
$allowedExtensions = array("pdf","doc","docx","gif","jpeg","jpg","png","rtf","txt");
$files = array();
$username=$_POST['username'];
$email=$_POST['email'];
//loop through all the files
foreach($_FILES as $name=>$file){
//define some variables
$file_name= $file['name'];
$temp_name= $file['tmp_name'];
//check if this file type is allowed
$path_parts = pathinfo($file_name);
$ext = $path_parts['extension'];
if(!in_array($ext,$allowedExtensions)) {
die("extension not allowed");
}
//move this file to the server
$server_file = "/home/public_html/xyz.com/uploads/$path_parts[basename]";
move_uploaded_file($temp_name,$server_file);
//add this file to array of files
array_push($files,$server_file);
}
//define some mail variables
$to = "info#xyz.com";
$from = "From: $username<$email>\r\nReturn-path: $email";
$subject = "Photo attachment of . $name .";
$msg = "Images of $username, $email";
$headers = "From: $from";
//define our boundary
$semi_rand = md5(time());
$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";
//tell the header about the boundary
$headers .= "nMIME-Version:1.0\n";
$headers .= "Content-Type: multipart/mixed;\n";
$headers .= " boundary=\"{$mime_boundary}\"";
//part1: define the plain text email
$message = "\n\n--{$mime_boundary}\n";
$message .="Content-Type: text/plain; charset=\"iso-8859-1\"\n";
$message .="Content-Transfer-Encoding: 7bit\n\n". $msg ."\n\n";
$message .="--{$mime_boundary}\n";
//part2: loop and define mail attachments
foreach($files as $file){
$aFile = fopen($file,"rb");
$data = fread($aFile,filesize($file));
fclose($aFile);
$data = chunk_split(base64_encode($data));
$message .="Content-Type: {\"application/octet-stream\"};\n";
$message .= " name=\"$files\"\n";
$message .= "Content-Disposition: attachment;\n";
$message .= " filename=\"$files\"\n";
$message .= "Content-Transfer-Encoding: base64\n\n" . $data . "\n\n";
$message .= "--{$mime_boundary}\n";
}
//send the email
$ok = mail($to, $subject, $message, $headers, $from);
if($ok){
header("Location: thank-your.php");
}
else{
echo"<p>mail could not be sent!</p>";
}
die();
}
?>

Make Attachment File Format only .txt .doc .docx

I create a PHP contact form with file attachment with helping a online tutorial. But i want to function it like user only upload .txt .doc .docx file format, no other format will be accepted.
<?php
$from = "name#example.com";
$to = $_POST['email'];
$subject =$_POST['subject'];
$message = $_POST['body'];
// Temporary paths of selected files
$file1 = $_FILES['file1']['tmp_name'];
$file2 = $_FILES['file2']['tmp_name'];
$file3 = $_FILES['file3']['tmp_name'];
// File names of selected files
$filename1 = $_FILES['file1']['name'];
$filename2 = $_FILES['file2']['name'];
$filename3 = $_FILES['file3']['name'];
// array of filenames to be as attachments
$files = array($file1, $file2, $file3);
$filenames = array($filename1, $filename2, $filename3);
// include the from email in the headers
$headers = "From: $from";
// boundary
$time = md5(time());
$boundary = "==Multipart_Boundary_x{$time}x";
// headers used for send attachment with email
$headers .= "\nMIME-Version: 1.0\n" . "Content-Type: multipart/mixed;\n" . " boundary=\"{$boundary}\"";
// multipart boundary
$message = "--{$boundary}\n" . "Content-Type: text/plain; charset=\"iso-8859-1\"\n" . "Content-Transfer-Encoding: 7bit\n\n" . $message . "\n\n";
$message .= "--{$boundary}\n";
// attach the attachments to the message
for($x=0; $x<count($files); $x++){
$file = fopen($files[$x],"r");
$content = fread($file,filesize($files[$x]));
fclose($file);
$content = chunk_split(base64_encode($content));
$message .= "Content-Type: {\"application/octet-stream\"};\n" . " name=\"$files[$x]\"\n" .
"Content-Disposition: attachment;\n" . " filename=\"$filenames[$x]\"\n" .
"Content-Transfer-Encoding: base64\n\n" . $content . "\n\n";
$message .= "--{$boundary}\n";
}
// sending mail
$sendmail = mail($to, $subject, $message, $headers);
// verify if mail is sent or not
if ($sendmail) {
echo "Sent successfully!";
} else {
echo "Error occurred. Try again!";
}
?>
the use of $_FILE["filename"]["type"] is not recomended for file type checking as the type parameter is browser specific i.e different browser can have different type So we will try to extract the format from the string function
$filename=$_FILES["file1"]["name"];//get the name of the file
$extension=strrchr($filename, ".");//extracting the extension
if($extension=".txt" || $extension=".doc" || $extension=".docx")
{
//send mail;
}
else
{
//error;
}
Simply,
$filename_array = explode(".",$filename);
$ext = ".".$filename_array[count($filename_array)-1];
if($ext!==".txt" && $ext!==".doc" && $ext!==".docx"):
//Do bad extension code
endif;
//Do code that passed extension validation
Hope this helps!
$allowed = array('.txt', '.doc', '.docx')
$fileNames = array();
$filename1= $_FILES['file1']['name'];
$ext1 = pathinfo($path, PATHINFO_EXTENSION);
if(in_array($ext1, $allowed)){
array_push($fileNames, $filename1); //repeat for 2, 3, etc...
}
function allowed_file(){
//Add the allowed mime-type files to an 'allowed' array
$allowed = array('application/doc', 'application/txt', 'another/type');
//Check uploaded file type is in the above array (therefore valid)
if(in_array($_FILES['file']['name'], $allowed))
{
// Your code
}
}
Reference : php file upload, how to restrict file upload type

Multiple Mail Attachments in PHP

I was wondering if I could pick your brain about something.
I have a mail script on my site that I can use to send emails with a single attachment. Sending a single attachment works just fine.
I want to be able to send an email with multiple attachments and I am running into problems doing so.
This is the file selection box I have in the form:
<input type="file" name="attachment[]" id="attachment[]" multiple onfocus="this.style.backgroundColor='#e7e7e7'" onblur="this.style.backgroundColor='#ffffff'"/>
Then, when the files are selected this is the php that handles it:
if (!empty($_FILES['attachment']['name']))
{
if(count($_FILES['attachment']['name'])>0)
{
$count = 0;
foreach ($_FILES['attachment']['name'] as $file)
{
$name_of_file = $_FILES['attachment']['name'][$count];
$file_name = $guid." - ".$name_of_file;
$temp_name = $_FILES['attachment']['tmp_name'][$count];
$file_type = $_FILES['attachment']['type'][$count];
$file_size = $_FILES['attachment']['size'][$count];
$count++;
if ($file_size > 2048000)
{
header ("refresh: 5; url=attach.php");
include ("header.php");
echo "File size is to big. Size must be no bigger than 2Mb. Please go <a href='attach.php'>back</a>";
include ("footer.php");
exit;
}
else
{
$pics = array(".bmp", ".gif", ".jpg", "jpeg", ".png"); //5
$docs = array(".doc", "docx", ".odt", ".pdf", ".ppt", "pptx", ".rtf", ".txt", ".xls", "xlsx"); //10
$misc = array(".csv", ".htm", "html", ".php", ".pkt", ".rar", ".sql", ".xpi", ".zip"); //9
$base = basename($file_name);
$extension = substr($base, strlen($base)-4, strlen($base));
$extension = strtolower($extension);
if (in_array($extension,$pics))
{
$target = "".FILES."/".FUP_PICS."/";
}
if (in_array($extension,$docs))
{
$target = "".FILES."/".FUP_DOCS."/";
}
if (in_array($extension,$misc))
{
$target = "".FILES."/".FUP_MISC."/";
}
$target = $target.$base;
$allowed_extensions = array(".bmp", ".csv", ".doc", "docx", ".gif", ".htm", "html",
".jpg", ".JPG", "jpeg", "JPEG", ".odt", ".pdf", ".php", ".pkt", ".png", ".ppt", "pptx",
".rtf", ".sql", ".txt", ".xls", "xlsx", ".zip"
);
if(in_array($extension,$allowed_extensions))
{
$from = mysql_real_escape_string($_POST['from']);
$emailto = mysql_real_escape_string($_POST['emailto']);
$bcc = mysql_real_escape_string($_POST['bcc']);
$subject = htmlspecialchars($_POST['subject']);
$message = htmlspecialchars($_POST['message'], ENT_NOQUOTES);
$message1 = htmlspecialchars_decode($_POST['message'], ENT_QUOTES);
if ($sendhash == 'Y')
{
$message1 .= "\n\nThe following is your unique message ID: ";
$message1 .= $guid;
$message1 .= "\n\nAttachment has been scanned for viruses and is virus free.";
$message1 .= "\n\nPlease make sure the first part of the file name matches the unique message ID. If it does not, please DO NOT open the file";
$message1 .= "\n\nTo verify the validity of the message, click the link below or copy and paste it into your browser:";
$message1 .= "\n\n ";
$message1 .= HTTP_PATH;
$message1 .= "verify.php?uid=";
$message1 .= urlencode($guid);
$message1 .= "\n\nPlease note, verification link expires on ";
$message1 .= $expirydate;
}
else
{
}
$message1 .= "\n\n--\nSent from Chris' Address Book";
foreach ($file as $files)
{
$files = $temp_name;
$content = chunk_split(base64_encode(file_get_contents($file)));
$uid = md5(uniqid(time()));
$header = "From: ".$from."\r\n";
$header .= "Reply-To: ".$from."\r\n";
$header .= "Bcc: ".$bcc."\r\n";
$header .= "MIME-Version: 1.0\r\n";
$header .= "Content-Type: multipart/mixed; boundary=\"".$uid."\"\r\n\r\n";
$header .= "This is a multi-part message in MIME format. \r\n";
$header .= "--".$uid."\r\n";
$header .= "Content-Transfer-Encoding: 7bit\r\n\r\n";
$header .= $message1."\r\n";
$header .= "--".$uid."\r\n";
$header .= "Content-Type: ".$file_type."; name=\"".$file_name."\"\r\n";
$header .= "Content-Transfer-Encoding: base64\r\n";
$header .= "Content-Disposition: attachment; filename=\"".$file_name."\"\r\n\r\n";
$header .= $content."\r\n";
}
if ($_POST['emailto'] == '')
{
$sqlp=mysql_query("SELECT * FROM ".PERSON." JOIN contact on contact.personID = person.adbkid WHERE email1 = '$bcc' OR email2 = '$bcc'");
$num=mysql_numrows($sqlp);
}
else
{
$sqlp=mysql_query("SELECT * FROM ".PERSON." JOIN contact on contact.personID = person.adbkid WHERE email1 = '$emailto' OR email2 = '$emailto'");
$num=mysql_numrows($sqlp);
}
while ($row = mysql_fetch_array($sqlp))
{
$adbkid = $row['adbkid'];
$id = $row['id'];
}
if ($num == 0)
{
$selfid = "EMAILSA";
}
else
{
$selfid = $adbkid;
}
if (mail($emailto, $subject, "", $header))
{
if ($sendhash == 'Y')
{
$sql=mysql_query("INSERT INTO ".EMAILS." (emailfrom, emailto, bcc, subject, message, getthedate, gettime, randhash, fileatt, fileext, showinsearch, expireit, showinverify, wasviewed, personID) VALUES ('$from', '$emailto', '$bcc', '$subject', '$message', '$getthedate', '$gettime', '$guid', '$file_name', '$extension', '$showinsearch', '$expireit', '$siv', '$wv', '$selfid')");
$lastid=mysql_insert_id();
$sqlr=mysql_query("INSERT INTO ".HASH." (randhash) VALUES ('$guid')");
}
else
{
$sql=mysql_query("INSERT INTO ".EMAILS." (emailfrom, emailto, bcc, subject, message, getthedate, gettime, fileatt, fileext, showinsearch, expireit, showinverify, wasviewed, personID) VALUES ('$from', '$emailto', '$bcc', '$subject', '$message', '$getthedate', '$gettime', '$file_name', '$extension', '$showinsearch', '$expireit', '$siv', '$wv', '$selfid')");
$lastid=mysql_insert_id();
}
$sqlone = "INSERT INTO ".SENTFILES." (filename, filetype, fileext, filesize, filetempname, dateadded, timeadded, fileguid, sentmailid) VALUES ('$file_name', '$file_type', '$extension', '$file_size', '$temp_name', '$getthedate', '$gettime', '$guid', '$lastid')";
$expire = mysql_query("UPDATE ".EMAILS." SET showinverify = 0 WHERE expireit < CURDATE()");
if (!mysql_query($sqlone,$conn))
{
die("Error: " . mysql_error().".");
}
header ("refresh: 5; url=$url");
include ("header.php");
$ful = (move_uploaded_file($temp_name, $target)) ? "".$file_name." was uploaded to ".$target."" : "".$file_name.", was not uploaded. Please try a manual upload.";
echo "<title>Success sending email</title>";
echo "Your message has been successfully sent. Message details have been added to the database.<p>$ful";
include ("footer.php");
}
else
{
header ("refresh: 5; url=$url");
include ("header.php");
echo "<title>Error sending email</title>";
echo "There seems to be an error sending your email.";
include ("footer.php");
}
exit;
}
else
{
header ("refresh: 5; url=attach.php");
include ("header.php");
echo "File type is not allowed. Please go <a href='attach.php'>back</a>";
include ("footer.php");
exit;
}
}
}
}
The problem I run in to is when I try to send an email this way, I get the following error:
Warning: Invalid argument supplied for foreach() in /home/flattley/public_html/chriswilcox/cab/attach.php on line 150
Line 150 is this:
foreach ($file as $files)
I just don't have any idea where I am going wrong. If I don't have the foreach loop there it doesn't send or it will only send the first file.
I know I could use something like phpmailer, but I want to be able to do this on my own. I just can't see where I am going wrong.
I have tried the script on my local apache at home without mailing it and it uploads and moves multiple files just fine - as it does on my host. It's when I add the mailing option that it all goes pear shaped.
Any help you could offer would be most appreciated
If you look back at your code:
foreach ($_FILES['attachment']['name'] as $file)
$file is already a single file name. It is not an array. As mentioned my php documentation.
I see that in your code, you try to get the content of uploaded files. To do that, you can do something like this:
foreach($_FILES['attachment']['tmp_name'] as $eachFile){
$content = chunk_split(base64_encode(file_get_contents($file)));
$uid = md5(uniqid(time()));
$header = "From: ".$from."\r\n";
$header .= "Reply-To: ".$from."\r\n";
$header .= "Bcc: ".$bcc."\r\n";
$header .= "MIME-Version: 1.0\r\n";
$header .= "Content-Type: multipart/mixed; boundary=\"".$uid."\"\r\n\r\n";
$header .= "This is a multi-part message in MIME format. \r\n";
$header .= "--".$uid."\r\n";
$header .= "Content-Transfer-Encoding: 7bit\r\n\r\n";
$header .= $message1."\r\n";
$header .= "--".$uid."\r\n";
$header .= "Content-Type: ".$file_type."; name=\"".$file_name."\"\r\n";
$header .= "Content-Transfer-Encoding: base64\r\n";
$header .= "Content-Disposition: attachment; filename=\"".$file_name."\"\r\n\r\n";
$header .= $content."\r\n";
}

PHP mailer script error

I have an submit page where client scan submit a fillable PDF form along with a photo, using the attached mailer script. The form uploads to the server correctly, however when it is sent to the client, the PDF is blank.
<?php
// did files get sent
if(isset($_FILES) && (bool) $_FILES) {
// define allowed extensions
$allowedExtensions = array("pdf","doc","docx","gif","jpeg","jpg","png","rtf","txt");
$files = array();
// loop through all the files
foreach($_FILES as $name=>$file) {
// define some variables
$file_name = $file['name'];
$temp_name = $file['tmp_name'];
// check if this file type is allowed
$path_parts = pathinfo($file_name);
$ext = $path_parts['extension'];
if(!in_array($ext,$allowedExtensions)) {
die("extension not allowed");
}
// move this file to the server YOU HAVE TO DO THIS
$server_file = "/home/castmeb1/public_html/uploads/$path_parts[basename]";
move_uploaded_file($temp_name,$server_file);
// add this file to the array of files
array_push($files,$server_file);
}
// define some mail variables
$to = "castmebg#gmail.com";
$from = "castmebg#gmail.com";
$subject ="test attachment";
$msg = "Please see attached";
$headers = "From: $from";
// define our boundary
$semi_rand = md5(time());
$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";
// tell the header about the boundary
$headers .= "\nMIME-Version: 1.0\n";
$headers .= "Content-Type: multipart/mixed;\n";
$headers .= " boundary=\"{$mime_boundary}\"";
// part 1: define the plain text email
$message ="\n\n--{$mime_boundary}\n";
$message .="Content-Type: text/plain; charset=\"iso-8859-1\"\n";
$message .="Content-Transfer-Encoding: 7bit\n\n" . $msg . "\n\n";
$message .= "--{$mime_boundary}\n";
// part 2: loop and define mail attachments
foreach($files as $file) {
$aFile = fopen($file,"rb");
$data = fread($aFile,filesize($file));
fclose($aFile);
$data = chunk_split(base64_encode($data));
$message .= "Content-Type: {\"application/octet-stream\"};\n";
$message .= " name=\"$file\"\n";
$message .= "Content-Disposition: attachment;\n";
$message .= " filename=\"$file\"\n";
$message .= "Content-Transfer-Encoding: base64\n\n" . $data . "\n\n";
$message .= "--{$mime_boundary}\n";
}
// send the email
$ok = mail($to, $subject, $message, $headers);
if ($ok) {
echo "<p>mail sent to $to!</p>";
} else {
echo "<p>mail could not be sent!</p>";
}
die();
}
?>
Thanks,
JB
if(isset($_FILES) && (bool) $_FILES) {
is an invalid test for a successful upload. The $_FILES array is always set, and assuming a file upload ATTEMPT was made, the array will NEVER be empty.
You should check for errors like this:
if ($_FILES['name_of_file_field']['error'] === UPLOAD_ERR_OK) {
... file was successfully uploaded ...
}
The error codes are defined here: http://php.net/manual/en/features.file-upload.errors.php

Categories