send email via php only once - php

i studying on PHP now, and want to learn how to send email from diretory web to someone email with attachment,,
i try with this code, and it worked, but when i try to send email again to other email address, it didnt send again and need a few hour (or few moment, i didnt know exactly, just my guess) to worked again. i didnt know what the real problem is?
if someone have same problem with me, please share here. thanks in advance. and sorry for my bad english.
this is my code,
<?php
session_start();
if (isset($_SESSION['xx']) && $_SESSION['xx'] == session_id() ) {
//panggil file config.php untuk menghubung ke server
include('config.php');
//catch data from the form
$nmMhs = $_POST['name'];
$sexMhs = (isset($_POST['sex']))?$_POST['sex']:"";
$almMhs = $_POST['address'];
$tlpMhs = $_POST['telp'];
$date=$_POST['tgl']; $month=$_POST['bln']; $year=$_POST['thn'];
$tgllhrMhs = $date.'-'.$month.'-'.$year;
$emlMhs = $_POST['email'];
$prodiMhs = (isset($_POST['prodi']))?$_POST['prodi']:"";
$statMhs = (isset($_POST['stat']))?$_POST['stat']:"";
$klsMhs = (isset($_POST['kelas']))?$_POST['kelas']:"";
$orgMhs = $_POST['org'];
$sakitMhs = $_POST['sick'];
$almetMhs = (isset($_POST['almet']))?$_POST['almet']:"";
$kausMhs = (isset($_POST['kaos']))?$_POST['kaos']:"";
//send email
$email_to = $emlMhs; // The email you are sending to (example)
$email_from = "someone#gmail.com"; // The email you are sending from (example)
$email_subject = "subject of the messages"; // The Subject of the email
$email_txt = "hello everybody, this is a message"; // Message that the email has in it
//email attachment
$fileatt = "path/file"; // Path to the file (example)
$fileatt_type = "application/msword"; // File Type
$fileatt_name = "file.docx"; // Filename that will be used for the file as the attachment
$file = fopen($fileatt,'rb');
$data = fread($file,filesize($fileatt));
fclose($file);
$semi_rand = md5(time());
$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";
$headers="From: $email_from"; // Who the email is from (example)
$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: 7bit\n\n" . $email_txt;
$email_message .= "\n\n";
$data = chunk_split(base64_encode($data));
$email_message .= "--{$mime_boundary}\n" .
"Content-Type: {$fileatt_type};\n" .
" name=\"{$fileatt_name}\"\n" .
"Content-Transfer-Encoding: base64\n\n" .
$data . "\n\n" .
"--{$mime_boundary}--\n";
//save data to database
if($prodiMhs == "S1 Manajemen"){
$query = mysql_query("insert into mhs_manajemen values(null, '$nmMhs', '$sexMhs', '$almMhs', '$tlpMhs', '$tgllhrMhs', '$emlMhs', '$prodiMhs', '$statMhs', '$klsMhs', '$orgMhs', '$sakitMhs', '$almetMhs', '$kausMhs' )") or die(mysql_error());
if ($query) {
mail($email_to,$email_subject,$email_message,$headers);
echo "<script type='text/javascript'>
window.alert('Data has been inputed')
window.location.href='isi_data.php';
</script>";
}
}
if($prodiMhs == "S1 Administrasi Niaga"){
$query = mysql_query("insert into mhs_administrasi values(null,'$nmMhs', '$sexMhs', '$almMhs', '$tlpMhs', '$tgllhrMhs', '$emlMhs', '$prodiMhs', '$statMhs', '$klsMhs', '$orgMhs', '$sakitMhs', '$almetMhs', '$kausMhs' )") or die(mysql_error());
if ($query) {
mail($email_to,$email_subject,$email_message,$headers);
echo "<script type='text/javascript'>
window.alert('Data has been inputed')
window.location.href='isi_data.php';
</script>";
}
}
} else {
session_destroy();
echo "<script type='text/javascript'>
window.alert('<b>Access denied! Please login first!<b>')
window.location.href='index.php';
</script>";
}
?>

If you use else if and else instead of just an if the script will only execute one of the 2 blocks of code. So try putting else if directly after the closing curly bracket of if($prodiMhs == "S1 Manajemen"){. Basicly change if($prodiMhs == "S1 Administrasi Niaga"){ to else if($prodiMhs == "S1 Administrasi Niaga"){ More info on elseif and else.
I hope this helps you.

Related

mail() is Incorrectly Sending Emails to cPanel Default Account

I purchased a domain from GoDaddy and linked it to Office 365 (via MX records). This means I have several email accounts in Outlook that are #mydomain.com.
Example Outlook accounts:
sales#mydomain.com
contact#mydomain.com
matt#mydomain.com
I can send/receive emails through those accounts.
My website is hosted on basic web hosting with a cPanel installation, which means I was given a "default" email account. For example: default#mydomain.com. I wrote a PHP script on my website (contact form) that sends emails via mail() to contact#mydomain.com.
However all the emails are sent to the default cPanel account default#mydomain.com instead of the Outlook account contact#mydomain.com.
To test, I tried sending the emails to my personal account that is not hosted on mydomain and it works as expected. Emails are sent instantly.
How come my website incorrectly send emails to the Outlook accounts? Thanks for your time.
EDIT:
The script was requested:
<?php
$uploadedFile = $statusMsg = '';
if (isset($_POST['submit']))
{
$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$message = $_POST['message'];
if(!empty($first_name) && !empty($last_name) && !empty($message))
{
if(filter_var($email, FILTER_VALIDATE_EMAIL))
{
$uploadStatus = 1;
if(!empty($_FILES["attach"]["name"]))
{
$targetDir = "uploads/";
$fileName = basename($_FILES["attach"]["name"]);
$targetFilePath = $targetDir . $fileName;
$fileType = pathinfo($targetFilePath,PATHINFO_EXTENSION);
if(move_uploaded_file($_FILES["attach"]["tmp_name"], $targetFilePath))
{
$uploadedFile = $targetFilePath;
}
else
{
$uploadStatus = 0;
$statusMsg = "Sorry, there was an error uploading your file.";
}
}
if($uploadStatus == 1)
{
$name = $first_name.' '.$last_name;
$mailTo = "contact#mydomain.com";//changed to my real outlook account
$htmlContent = '<h2>Contact Request Submitted</h2>
<p><b>Name:</b> '.$name.'</p>
<p><b>Email:</b> '.$email.'</p>
<p><b>Phone:</b> '.$phone.'</p>
<p><b>Message:</b><br/>'.$message.'</p>';
// Header for sender info
$headers = "From: $name"." <".$email.">";
if(!empty($uploadedFile) && file_exists($uploadedFile))
{
// 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 = "--{$mime_boundary}\n" . "Content-Type: text/html; charset=\"UTF-8\"\n" .
"Content-Transfer-Encoding: 7bit\n\n" . $htmlContent . "\n\n";
// Preparing attachment
if(is_file($uploadedFile)){
$message .= "--{$mime_boundary}\n";
$fp = #fopen($uploadedFile,"rb");
$data = #fread($fp,filesize($uploadedFile));
#fclose($fp);
$data = chunk_split(base64_encode($data));
$message .= "Content-Type: application/octet-stream; name=\"".basename($uploadedFile)."\"\n" .
"Content-Description: ".basename($uploadedFile)."\n" .
"Content-Disposition: attachment;\n" . " filename=\"".basename($uploadedFile)."\"; size=".filesize($uploadedFile).";\n" .
"Content-Transfer-Encoding: base64\n\n" . $data . "\n\n";
}
$message .= "--{$mime_boundary}--";
$returnpath = "-f" . $email;
// Send email
$mail = mail($mailTo, "Contact Form Submission from ".$name, $message, $headers, $returnpath);
// Delete attachment file from the server
#unlink($uploadedFile);
}
else
{
// Set content-type header for sending HTML email
$headers .= "\r\n". "MIME-Version: 1.0";
$headers .= "\r\n". "Content-type:text/html;charset=UTF-8";
// Send email
$mail = mail($mailTo, 'Contact Form Submission from '.$name, $htmlContent, $headers);
}
// If mail sent
if($mail)
{
$statusMsg = "Your message has been sent. Thanks!";
}
else
{
$statusMsg = 'Your contact request submission failed, please try again.';
}
}
}
else
{
$statusMsg = 'Please enter a valid email address.';
}
}
else
{
$statusMsg = "Please fill out the required information.";
}
}
?>
The solution was to change my cPanel "Email Routing" option to "Remote" in order for all local emails to first check with the MX records.

Trying to send attachments with PHP mail()

I'm trying to store an uploaded file from a form to the uploads folder as well as send the file as an attachment to an email. The email sends perfectly fine and there is also an attachment, however the attachment is unreadable/corrupted.
I have tried with multiple file types and that makes no difference, I still have the same errors.
<?php
//Store File
if (!empty($_FILES) && isset($_FILES['upload'])) {
switch ($_FILES['upload']["error"]) {
case UPLOAD_ERR_OK:
$target = "uploads/";
$target = $target . basename($_FILES['upload']['name']);
if (move_uploaded_file($_FILES['upload']['tmp_name'], $target)) {
$status = "The file " . basename($_FILES['upload']['name']) . " has been uploaded";
$imageFileType = pathinfo($target, PATHINFO_EXTENSION);
} else {
$status = "Sorry, there was a problem uploading your file.";
}
break;
}
echo "Status: {$status}<br/>\r\n";
}
$fileatt = getcwd() . "/uploads"; // Path to the file
$fileatt_type = "application/pdf"; // File Type
$fileatt_name = $_FILES['upload']['name']; // Filename that will be used for the file as the attachment
$email_from = $_POST['email']; // Who the email is from
$email_subject = "Your attached file"; // The Subject of the email
$email_message = "Thanks for visiting mysite.com! Here is your free file.";
$email_message .= "Thanks for visiting."; // Message that the email has in it
$email_to = 'test#test.com'; // Who the email is to
$headers = "From: " . $email_from;
$file = fopen($fileatt . "/" . $fileatt_name, 'rb');
$data = fread($file, filesize($fileatt . "/" . $fileatt_name));
fclose($file);
$semi_rand = md5(time());
$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";
$headers .= "\r\nMIME-Version: 1.0\r\n" . "Content-Type: multipart/mixed;\r\n" . " boundary=\"{$mime_boundary}\"";
$email_message .= "This is a multi-part message in MIME format.\r\n\r\n" . "--{$mime_boundary}\r\n" . "Content-Type:text/html; charset=\"iso-8859-1\"\r\n" . "Content-Transfer-Encoding: 7bit\r\n\r\n" . $email_message .= $_POST['email'] . "<br>" . $_POST['firstname'] . "<br>" . $_POST['surname'] . "<br>" . $_POST['degree'] . "<br>" . "\r\n\r\n";
$data = chunk_split(base64_encode($data));
$email_message .= "--{$mime_boundary}\r\n" . "Content-Type: {$fileatt_type};\r\n" . " name=\"{$fileatt_name}\"\r\n" . "Content-Disposition: attachment;\r\n" . " filename=\"{$fileatt_name}\"\r\n" . "Content-Transfer-Encoding: base64\r\n\r\n" . $data .= "\r\n\r\n" . "--{$mime_boundary}--\r\n";
$ok = mail($email_to, $email_subject, $email_message, $headers);
if ($ok) {
echo "You file has been sent
to the email address you specified.
Make sure to check your junk mail!
Click here to return to mysite.com.";
} else {
die("Sorry but the email could not be sent. Please go back and try again!");
}
?>
Please could somebody point me in the right direction?
You can find the solution here.
Explained completely to need to ass same info again.
Solution

PHP Form attach CSV

I've been searching all day and have not found the code that works. I'm trying, after submitting form,
Validate - This works
Check to see if record exists - This works
Insert record - This works
Attach a CSV that has the form variables - This does not work
This is a scaled down version
<?php
$to = "email#email.com";
if(isset($_POST['submit']))
{
// VALIDATION
if(empty($_POST['address']))
{
"First Name Required";
}
if(empty($_POST['email']))
{
"Last Name Required";
}
if(empty($error))
{
$subject = 'The Form';
$headers = "MIME-Version: 1.0 \r\n";
$headers .= "Content-Type: text/html; \r\n" ;
$headers .= "From: from#theemailaddress.com\r\n"."Reply-to: {$_POST['email']}\r\n";
$msg .="<html>
<head></head>
<body>
<table>
<tr><td>
<table>
<tr><td>This is the email sent.</td></tr>
</table>
</body>
</html>";
include('con.php');
$con = mysqli_connect($host,$user,$pass,$dbName);
if (!$con)
{
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,"thetable");
$email= mysqli_real_escape_string($con, $_POST['email']);
$address= mysqli_real_escape_string($con, $_POST['address']);
$sql = "SELECT * FROM thetable WHERE `email` = '{$email}' OR `address` = '{$address}'";
$result = mysqli_query($con,$sql);
if(($result->num_rows)>= 1)
{
$theerror = "You exist";
}
else
{
$sql="INSERT INTO thetable(email, address) VALUES ('$_POST[email]','$_POST[address]'";
$success = "Sent ... Insert it!!!";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
//The Attachment
$cr = "\n";
$data = "Email" . ',' . "address" . ',' . $cr;
$data .= "$email" . ',' . "$address" . $cr;
$fp = fopen('diploma_apprenticeship_form_sub.csv','a');
fwrite($fp,$data);
fclose($fp);
$attachments[] = Array(
'data' => $data,
'name' => 'diploma_apprenticeship_form_sub.csv',
'type' => 'application/vnd.ms-excel'
);
//Generate a boundary string
$semi_rand = md5(time());
$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";
//Add the headers for a file attachment
$headers = "MIME-Version: 1.0\n" .
"From: {$from}\n" .
"Content-Type: multipart/mixed;\n" .
" boundary=\"{$mime_boundary}\"";
//Add a multipart boundary above the plain message
$msg= "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: 7bit\n\n" .
$text . "\n\n";
//Add sttachments
foreach($attachments as $attachment){
$data = chunk_split(base64_encode($attachment['data']));
$name = $attachment['name'];
$type = $attachment['type'];
$msg.= "--{$mime_boundary}\n" .
"Content-Type: {$type};\n" .
" name=\"{$name}\"\n" .
"Content-Transfer-Encoding: base64\n\n" .
$data . "\n\n" ;
}
$msg.= "--{$mime_boundary}--\n";
$result = #mail($to, $subject, $msg, $headers);
}
mysqli_close($con);
{
}
}
}
?>
Try this,
$f = fopen('path to file', 'w'); //path such as __DIR__./file.csv'; write mode.
fputcsv( $f, $data);
//data is an array of data ie array('one', 'two'); is one,two in the file ~ make a loop
//around this and write as many lines as you need, like array(header, header1); then
//array(data, data1) etc...
fclose($f); //close the file when done
http://phpmailer.worxware.com/
require 'PHPMailerAutoload.php';
$mail = new PHPMailer;
$mail->From = 'from#example.com';
$mail->addAddress('joe#example.net', 'Joe User');
$mail->addAttachment( __DIR__.'/file.csv');
$mail->Subject = 'Here is the subject';
$mail->Body = 'This is the HTML message body <b>in bold!</b>';
$mail->send();
unlink( __DIR__.'/file.csv' ); //remove the file
Oh and get rid of all that header stuff, let php mailer do its job, which as you mentioned is not to validate your data. Work up a process flow.
Input
Validate
Calculate ( assign values )
Output ( send your email )
Clean up ( remove any files, etc.. )
etc..
AS An update
$msg .="<html>
<head></head>
<body>
<table>
<tr><td>
<table>
<tr><td>This is the email sent.</td></tr>
</table>
</body>
</html>";
... and then latter
$msg= "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: 7bit\n\n" .
$text . "\n\n";
Also your likely to get a warning for the first message as you are not defining the variable before using the concant on it.
$msg .= 'something';
Should be
$msg = 'something';
Or
$msg = '';
$msg .= 'something';

PHP Contact Form w/ File Upload Attachment

I have a simple PHP contact form (Seen Here) that I want to add a file upload option to, so clients can attach an important document and mail it to me using PHP's mail function.
The form works fine on its own, but I can't seem to get the code right for uploading the attachment, storing it temporarily on the server and sending it to me as part of the e-mail. Here is the code I'm using:
<?php
if ($_POST['test'] != '') {
echo 'Unfortunately, by filling out the hidden field, you have been identified as a potential spambot and your message has been terminated.';
} else {
//Validate the name:
if (!empty($_POST['name'])) {
$name = $_POST['name'];
} else {
echo "You forgot to enter your name.<br>";
}
//Validate the phone:
if (!empty($_POST['phone'])) {
$phone = $_POST['phone'];
} else {
echo "You forgot to enter your phone number.<br>";
}
//Validate the e-mail:
if (!empty($_POST['email'])) {
$email = $_POST['email'];
} else {
echo "You forgot to enter your e-mail.<br>";
}
//Validate the message:
if (!empty($_POST['message'])) {
$message = $_POST['message'];
} else {
echo "You forgot to enter a message.";
}
if (!empty($_POST['name']) && !empty($_POST['phone']) && !empty($_POST['email']) && !empty($_POST['message'])) {
// Obtain file upload variables:
$attachment = $_FILES['attachment']['tmp_name'];
$attachment_type = $_FILES['attachment']['type'];
$attachment_name = $_FILES['attachment']['name'];
if (file($attachment)) {
// Read the file to be attached ('rb' = read binary):
$file = fopen($attachment,'rb');
$data = fread($file,filesize($attachment));
fclose($file);
// Generate a boundary string:
$semi_rand = md5(time());
$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";
// Add the headers for a file attachment:
$headers = "\nMIME-Version: 1.0\n" .
"Content-Type: multipart/mixed;\n" .
" boundary=\"{$mime_boundary}\"";
// Add a multipart boundary above the plain message:
$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";
// Base64 encode the file data:
$data = chunk_split(base64_encode($data));
// Add file attachment to the message:
$message .= "--{$mime_boundary}\n" .
"Content-Type: {$attachment_type};\n" .
" name=\"{$attachment_name}\"\n" .
//"Content-Disposition: attachment;\n" .
//" filename=\"{$attachment_name}\"\n" .
"Content-Transfer-Encoding: base64\n\n" .
$data . "\n\n" .
"--{$mime_boundary}--\n";
}
$body = "$name\n$phone\n$email\n\n$message";
mail("*#*.com", "Starcrest Escrow, Inc. Website - Real Property Sale", $body, $headers);
header("Location: confirm.html");
}
}
?>
When I run this script presently, it forwards me to the confirmation page, but no e-mail appears to be generated at all. What am I doing wrong?
<?php
if (isset($_POST['txtEmail'])) {
// EDIT THE 2 LINES BELOW AS REQUIRED
$email_to = "xyz#abc.com";
$email_subject = "Subject";
$email_from = "abc#xyz.com";
function died($error)
{
// your error code can go here
echo "We are very sorry, but there were error(s) found with the form you submitted. ";
echo "These errors appear below.";
echo $error . "<br /><br />";
echo "Please go back and fix these errors.<br /><br />";
die();
}
// validation expected data exists
if (!isset($_POST['txtName']) || !isset($_POST['txtEmail']) || !isset($_POST['txtAddress']) || !isset($_POST['txtContact']) || !isset($_POST['txtUpload'])) {
died('We are sorry, but there appears to be a problem with the form you submitted.');
}
$name = $_POST['txtName']; // required
$email = $_POST['txtEmail']; // required
$address = $_POST['txtAddress']; // required
$contact = $_POST['txtContact']; // not required
$upload = $_POST['txtUpload']; // required
$email_message = "Form Details are below.\n\n";
function clean_string($string)
{
$bad = array(
"content-type",
"bcc:",
"to:",
"cc:",
"href"
);
return str_replace($bad, "", $string);
}
$email_message.= "Full Name: " . clean_string($name) . "\n\n";
$email_message.= "Address: " . clean_string($address) . "\n\n";
$email_message.= "Email ID: " . clean_string($email) . "\n\n";
$email_message.= "Contact No.: " . clean_string($contact) . "\n\n";
$email_message.= "File: " . clean_string($upload) . "\n\n";
// create email headers
$headers = 'From: ' . $email_from . "\r\n" . 'Reply-To: ' . $email . "\r\n" . 'X-Mailer: PHP/' . phpversion();
#mail($email_to, $email_subject, $email_message, $headers);
?>
<!-- include your own success html here -->
Thank you for contacting us. We will be in touch with you very soon.
<?php
}
?>

test PHP mail()

I have a mail submission script that is working exactly as expected on both a dev environment and live with one exception. I am getting conflicting results from the mail() test conditional on the live environment vs the dev environment.
On my dev environment it redirects to $ThanksURL on success. On the live server even through the mail is successfully the script proceeds to the else statement and redirects back to the form page.
This has been driving me crazy so any ideas as to why would be most welcome.
Snippet of the issue:
$ok = #mail($to, $subject, $message, $headers, $returnpath);
if($ok){ header("Location: $ThanksURL");
exit;
}else{ $_SESSION['error'] .= " There has been a problems submitting your details. <br />";
header("Location: $form");
exit;
}// end if ok
Script in full:
<?php
session_start();
$form = 'index.php';
$_SESSION['error'] = "The following errors have occured: ";
if(isset($_POST['submitted'])) {
// email fields: to, from, subject, and so on
// Here
$from = "Form Feedback <******#gmail.com>";
$to = "******#gmail.com";
$subject = "Competition";
$ThanksURL = "thankyou.html";
$headers = "From: $from";
$returnpath = "-f" . $from;
$attachment = 0; // is there an attachement
//form fields
$emailAddress = stripslashes($_POST['email']);
$phone = stripslashes($_POST['phone']);
$comments = stripslashes($_POST['comments']);
//basic message info
$message = "Info submitted:\n\nEmail address: " .$emailAddress ."\n\nPhone number: " .$phone."\n\nComments:\n ".$comments. "\n\n";
if($_FILES['attachment']['error'] == 4) {
$message .="No attachement included";
}else{
// test file type and size for submission
$allowedExts = array("doc", "docx", "pdf", "txt");
$extension = end(explode(".", $_FILES['attachment']["name"]));
if ((($_FILES['attachment']["type"] == "application/msword")
|| ($_FILES['attachment']["type"] == "application/vnd.openxmlformats-officedocument.wordprocessingml.document")//docx mime
|| ($_FILES['attachment']["type"] == "application/pdf")
|| ($_FILES['attachment']["type"] == "application/plain")
|| ($_FILES['attachment']["type"] == "text/plain"))
&& ($_FILES['attachment']["size"] < 2097152 )
&& in_array($extension, $allowedExts)){
// 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 = "--{$mime_boundary}\n" . "Content-Type: text/plain; charset=\"iso-8859-1\"\n"."Content-Transfer-Encoding: 7bit\n\n" . $message . "\n\n";
// prepare the files uplaod
$message .= "--{$mime_boundary}\n";
$fp = #fopen($_FILES['attachment']['tmp_name'],"rb");
$data = #fread($fp,filesize($_FILES['attachment']['tmp_name']));
#fclose($fp);
$data = chunk_split(base64_encode($data));
$message .= "Content-Type: application/octet-stream; name=\"".$_FILES['attachment']['name']."\"\n"."Content-Description: ".$_FILES['attachment']['name']."\n" ."Content-Disposition: attachment;\n" . " filename=\"".$_FILES['attachment']['name']."\";size=".$_FILES['attachment']['size'].";\n"."Content-Transfer-Encoding: base64\n\n" . $data . "\n\n";
$message .= "--{$mime_boundary}--";
}else{
$_SESSION['error'] .= "Error: " . $_FILES["attachment"]["name"] . " is not a doc, docx, pdf or txt file or is larger than 2mb. Please resubmit <br />";
header("Location: $form");
exit;
}
}//file conditional
//prepare mail
$ok = #mail($to, $subject, $message, $headers, $returnpath);
if($ok){
header("Location: $ThanksURL");
exit;
}else{
$_SESSION['error'] .= " There has been a problems submitting your details. <br />";
header("Location: $form");
exit;
}// end if ok
}// end sub
?>
Sorry to say this, but php mail can return something else on success than true or false, like mentioned in the php manual comment. Also, it is known to return false on success on some situations, too.
PHP mail() is a kludgy function from many different angles, and personally I would advise against using it in production systems. There are quite a few alternatives, such as swift mailer, PHP mailer, Zend_Mail etc.
However, if you want to use it, you should definitely log the actions and in this case, return values, and not have # to hide your return values.
As a summary, in this case mail() returned an empty string, and not true or false.

Categories