I am using the following code to email the results of a form submission. Since I'm running without a database I'd like some sort of other record.
<?php
$to = "me#me.com";
$from = $_REQUEST['email'];
$name = $_REQUEST['name'];
$headers = "From: $from";
$subject = "New Message";
$fields = array();
$fields{"first_name"} = "first_name";
$fields{"last_name"} = "last_name";
$fields{"email"} = "email";
$fields{"phone"} = "phone";
$fields{"hospital"} = "hospital";
$fields{"title"} = "title";
$body = "Here is what was sent:\n\n";
foreach($fields as $a => $b){
$body .= sprintf("%20s: %s\n",$b,$_REQUEST[$a]);
}
$send = mail($to, $subject, $body, $headers);
?>
How do I save the results to a text file in addition to email? I've seen examples on how to do text but not in addition to email.
you should check the file functions :
http://php.net/manual/en/function.fread.php
http://php.net/manual/en/function.fopen.php
http://php.net/manual/en/function.fwrite.php
http://php.net/manual/en/function.file-get-contents.php
http://php.net/manual/en/function.file-put-contents.php
An example of what you could do :
$filePath = 'records.txt';
file_put_contents($filePath, "\nYour text here...", FILE_APPEND);
Should be something like this:
//Email code here...
if(!$file = fopen('records.txt', 'a+')) {
echo 'Could not write to file.';
exit;
}
$content = "Email sent on: " . time() . PHP_EOL . "***" . PHP_EOL . $body . PHP_EOL . "***" . PHP_EOL;
if(fwrite($file, $content) === false) {
echo 'Could not write to file.';
exit;
}
fclose($file);
For more see examples at: http://php.net/fwrite
Related
I am trying to email piping with cpanel and PHP script. Its working fine. I am looking for get From Address, Subject and Message from received email. My script is like below
#!/usr/bin/php -q
<?php
/*$fd = fopen( "php://stdin", "r" );
$message = "";
while ( !feof( $fd ) )
{
$message .= fread( $fd, 1024 );
}
fclose( $fd );*/
$fd = fopen("php://stdin", "r");
$message = "";
while (!feof($fd)) {
$message .= fread($fd, 1024);
}
fclose($fd);
//split the string into array of strings, each of the string represents a single line, received
$lines = explode("\n", $message);
// initialize variable which will assigned later on
$from = "";
$subject = "";
$headers = "";
$message = "";
$is_header= true;
//loop through each line
for ($i=0; $i < count($lines); $i++) {
if ($is_header) {
// hear information. instead of main message body, all other information are here.
$headers .= $lines[$i]."\n";
// Split out the subject portion
if (preg_match("/^Subject: (.*)/", $lines[$i], $matches)) {
$subject = $matches[1];
}
//Split out the sender information portion
if (preg_match("/^From: (.*)/", $lines[$i], $matches)) {
$from = $matches[1];
}
} else {
// content/main message body information
$message .= $lines[$i]."\n";
}
if (trim($lines[$i])=="") {
// empty line, header section has ended
$is_header = false;
}
}
$to = 'myemail#gmail.com';
$subject = 'the subject';
$message1 = "You have new message from :".$from. "and message is" .$message;
$headers = 'From: webmaster#mydomain.com' . "\r\n" .
'Reply-To: webmaster#mydomain.com' . "\r\n" .
'X-Mailer: PHP/' . phpversion();
mail($to, $subject, $message1, $headers);
?>
I am getting result in my email like below
You have new message from :FirstName LastName <senderemail#gmail.com>and message is--00000000000045a1e5059ef97af8
Content-Type: text/plain; charset="UTF-8"
This is Body text Message
--00000000000045a1e5059ef97af8
Content-Type: text/html; charset="UTF-8"
<div dir="ltr"><div class="gmail_default" style="font-family:georgia,serif;font-size:large">This is text<br></div></div>
--00000000000045a1e5059ef97af8--
However its contain unnecessary words in it. I want plain output like below
You have new message from :senderemail#gmail.com and message is This is Body text Message
Sorry I am new in PHP and does not able to solve the issue. Let me know if anyone can help me for extract and get output like this.
Thanks!
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);
}
?>
I am writing an application that is to send an email that contains a CSV as an attachment. However, it is not working. The mail function does not return false (implying that it succeeded); however, the email is not being sent.
I have sent/received email from the server before, so I do not believe that is the issue. However, I do not really have any experience with sending attachments through PHP, so I would suspect the issue lies in there. I have followed this tutorial to an extent: http://www.texelate.co.uk/blog/post/56-send-an-email-attachment-with-php/
Here are some code snippets:
$file = tmpfile();
// code omitted
$fileArray = array(); // this gets filled with more arrays/lines of data
// code omitted
try {
foreach($fileArray as $line) {
var_dump($line);
fputcsv($file, $line);
}
// begin mailing
$toEmail = 'myemail';
$subject = "Insurance Registration";
fseek($file, 0);
$attachData = fread($file, 1024);
$fileName = $lastName . "_" . date('Y');
$random = md5(time());
$boundary = "==Multipart_Boundary_x{$random}x";
$headers = "From: Test \nMIME-Version: 1.0\n" . "Content-Type: multipart/mixed\n" . "boundary=\"{$boundary}\"";
$message = "Testing!.\n\n " . "-{$boundary}\n " . "Content-Type= text/plain; charset=\"iso-8859-1\n" . "Content-Transfer-Encoding 7bit\n\n " . "Testing Again " . "\n\n ";
$attachData = chunk_split(base64_encode($attachData));
$message .= "--{$boundary}\n" . "Content-Type: text/plain;\n" . "name=\"{$fileName}\"\n" . "Content-Disposition: attachment;\n" . " filename=\"{$fileName}\"\n" . " . Content-Transfer-Encoding: base64\n\n" . $attachData . "\n\n" . "-{$boundary}-\n";
} catch (Exception $e) {
echo $e->getMessage();
}
if(mail($toEmail, $subject, $message, $headers)) {
} else {
$hasError = true;
}
if($hasError) {
echo "<h2>Error Submitting form. Please check your input and try again</h2>";
} else {
header('Location: success.php');
}
I get redirected to the success page, but never receive an email. Thanks!
I am trying to create an order form which when complete, passes you on to the order.php page (sends the email), where you are then passed on to paypal. Everything was working fine until i tried to add attachments, when i added the code for attachment, the email is no longer sent.
<?php
$to = 'hidden' ;
$from = $_REQUEST['email'] ;
$name = $_REQUEST['name'] ;
$headers = "From: $from";
$subject = "Distinctive Writers - Contact Form";
$tprice = $_REQUEST['tprice'] ;
$fields = array();
$fields{"name"} = "name";
$fields{"email"} = "email";
$fields{"number"} = "number";
$fields{"subject"} = "subject";
$fields{"doctype"} = "doctype";
$fields{"spec"} = "spec";
$fields{"grade"} = "grade";
$fields{"days"} = "days";
$fields{"due"} = "due";
$fields{"pages"} = "pages";
$fields{"price"} = "price";
$mime_boundary="==Multipart_Boundary_x".md5(mt_rand())."x";
$tmp_name = $_FILES['filename']['tmp_name'];
$type = $_FILES['filename']['type'];
$file_name = $_FILES['filename']['name'];
$size = $_FILES['filename']['size'];
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)){
// Now Open the file for a binary read
$file = fopen($tmp_name,'rb');
// Now read the file content into a variable
$data = fread($file,filesize($tmp_name));
// close the file
fclose($file);
// Now we need to encode it and split it into acceptable length lines
$data = chunk_split(base64_encode($data));
}
// 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}\"";
// 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 and set another boundary to indicate that the end of the file has been reached
$message .= "--{$mime_boundary}\n" .
"Content-Type: {$type};\n" .
" name=\"{$file_name}\"\n" .
//"Content-Disposition: attachment;\n" .
//" filename=\"{$fileatt_name}\"\n" .
"Content-Transfer-Encoding: base64\n\n" .
$data . "\n\n" .
"--{$mime_boundary}--\n";
$body = "We have received the following information:\n\n"; foreach($fields as $a => $b){ $body .= sprintf("%20s: %s\n",$b,$_REQUEST[$a]); }
$headers2 = "From: noreply#YourCompany.com";
$subject2 = "Thank you for contacting us";
$autoreply = "Thank you for contacting us. Somebody will get back to you as soon as possible, usualy within 48 hours. If you have any more questions, please consult our website at www.oursite.com";
if($from == '') {print "You have not entered an email, please go back and try again";}
else {
if($name == '') {print "You have not entered a name, please go back and try again";}
else {
$send = mail($to, $subject, $body, $headers, $message);
$send2 = mail($from, $subject2, $autoreply, $headers2);
}
}
if(!mail($to, $subject, $body, $headers, $message)){
print "ERROR!!";
}
}
?>
I recommend PHPMailer too as mentioned by pc-shooter
then you can use
$mail = new PHPMailer();
then you can utilize either one of these two
$mail->AddStringAttachment($string,$filename)
$mail->AddAttachment($path);
Something to keep in mind, something else might be blocking the email. if the mail function returns TRUE then the mail was dispatched.
I am new to PHP not an expert by any means. Anyhow, I am building a PHP and HTML contact form and I am getting mixed up on the way to validate field input (trim, strip, htmlspecchars..). Anyways, here is my code, please go easy on me, I am a noob at this.
<?php
// define variables and set to empty values
$name = $email = $web = $telephone = $pages = $completion_date = $update_option = $hosting_option = $domain_option = $text = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = test_input($_POST["name"]);
$email = test_input($_POST["email"]);
$web = test_input($_POST["web"]);
$telephone = test_input($_POST["telephone"]);
$pages = test_input($_POST["pages"]);
$completion_date = test_input($_POST["completion_date"]);
$update_option = test_input($_POST["update_option"]);
$hosting_option = test_input($_POST["hosting_option"]);
$domain_option = test_input($_POST["domain_option"]);
$text = test_input($_POST["text"]);
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
$msg = $name . "\n";
$msg = $email . "\n";
$msg = $web . "\n";
$msg = $telephone . "\n";
$msg = $pages . "\n";
$msg = $completion_date . "\n";
$msg = $update_option . "\n";
$msg = $hosting_option . "\n";
$msg = $domain_option . "\n";
$msg = $text . "\n";
$recipient = "myemail#mydomain.com";
$subject = "Contact Has Been Made..";
$mailheaders = "MIME-Version: 1.0" . "\r\n";
$mailheaders = "Content-type:text/html;charset=iso-8859-1" . "\r\n";
$mailheaders = "From: <myemail#mydomain.com>, Reply-To: <myemail#mydomain.com>" . "\r\n";
$mailheaders = "Cc: <$email>" . "\r\n";
mail($recipient, $subject, $msg, $mailheaders);
?>
It looks okay until the definition of $msg, you keep overwriting it.
Prepend the equals (=) signs after the first with a dot (.)
$msg = $name . "\n";
$msg .= $email . "\n";
$msg .= $web . "\n";
... etc
stripslashes and htmlspecialchars are unnecessary in this context. After all, you are not outputting any HTML that contain the POSTed values.
The problem with your form validation is that I could write anything in the email field, for example, and it would still validate. You should make a case-by-case validation for all the fields so, for example with the email field
if (filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
// The email is valid
$email = $_POST['email'];
}
And so on. If you don't need them to be what they say the are, you can omit this. Other than that it looks okay.