I am using the code below from a tutorial to send files attached to a form on my website. I have added some variables which were missing and the form is working fine now. But the thing is I can't sent the form WITHOUT a file attached, after pressing the send button browser shows only a blank page with no message.
Other think I would like you to help is the email address. If I am writing not correct email address, it sends the form anyway.
Thanks in advance.
<?php
if ($_SERVER['REQUEST_METHOD']=="POST"){
$to="mymail#example.com";
$subject="You have got an email from TGS";
$from = stripslashes($_POST['fname'])."<".stripslashes($_POST['email']).">";
if(empty($_POST['fname']) || empty($_POST['email']) || empty($_POST['message']))
{
$errors .= "\n Error: all fields are required";
}
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$email = $_POST['email'];
$company = $_POST['company'];
$phone = $_POST['phone'];
$message = $_POST['message'];
if (!eregi( "^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $email))
{
$errors .= "\n Error: Invalid email address";
}
$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'];
$message = "\n\n First Name: $fname \n\n Last Name: $lname \n\n Company: $company \n\n Phone: $phone \n\n Email: $email \n\nMessage: \n\n $message \n\nHere is your file: $file_name";
if (file_exists($tmp_name)){
if(is_uploaded_file($tmp_name)){
$file = fopen($tmp_name,'rb');
$data = fread($file,filesize($tmp_name));
fclose($file);
$data = chunk_split(base64_encode($data));
}
$headers = "From: $from\r\n" .
"MIME-Version: 1.0\r\n" .
"Content-Type: multipart/mixed;\r\n" .
" boundary=\"{$mime_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" .
"Content-Type: {$type};\n" .
" name=\"{$file_name}\"\n" .
"Content-Transfer-Encoding: base64\n\n" .
$data . "\n\n" .
"--{$mime_boundary}--\n";
if (#mail($to, $subject, $message, $headers))
{
echo '<div><center><h1>Mail Sent successfully !!</h1></center></div>';
}else
{
echo '<div><center><h1>Error !! Unable to send Mail..</h1></center></div>';
}
}
}
?>
Related
Please help me to make code message in line break. i didn't know how to do this please check my code. hope you help me out. thanks alot in advance:-
<?php
if(isset($_POST['submit'])){
$to = "mymail#gmail.com"; // this is your Email address
$from = $_POST['name']; // this is the sender's Email address
$first_name = $_POST['name'];
$mail=$_POST['email'];
$msg=$_POST['message'];
$phone= $_POST['mob'];
$subject = "contact";
$subject2 = "Copy of your form submission";
$message = "Name:-". $first_name . "Email:-". $mail . "Phone Number:-
".$phone. " Message:-".$msg." " ;
$headers = "From:" . $from;
$headers2 = "From:" . $to;
mail($to,$subject,$message,$headers);
?>
I want to recieve message like this:-
Name:-loreal
email:- Mymail
phone Number:- 987654321
Message:- Hi
Try using \n in your message as:
$message = " Name:-". $first_name . "\n Email:-". $mail . "\n Phone Number:-
".$phone. "\n Message:-".$msg." " ;
They're escape sequences. \n is a newline and \r is a carriage return. \r is a Carriage Return \n is a Line Feed (or new line)
Mac: \r
Linux/Unix: \n
Windows: \r\n
When you are using html tags in email template then you have to mention content type in headers and you have to include that headers in mail function like this
$headers = 'MIME-Version: 1.0' . "\r\n";$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
mail($to,$subject,$message,$headers);
For HTML mail use proper headers:
<?php
if(isset($_POST['submit'])){
$to = "mymail#gmail.com"; // this is your Email address
$from = $_POST['name']; // this is the sender's Email address
$first_name = $_POST['name'];
$mail=$_POST['email'];
$msg=$_POST['message'];
$phone= $_POST['mob'];
$subject = "contact";
$message = "Name:-". $first_name . "<br/>Email:-". $mail . "<br/>Phone Number:-".$phone. "<br/>Message:-".$msg." " ;
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
mail($to,$subject,$message,$headers);
?>
<?php
if(isset($_POST['submit'])){
$to = "mymail#gmail.com"; // this is your Email address
$from = $_POST['name']; // this is the sender's Email address
$first_name = $_POST['name'];
$mail = $_POST['email'];
$msg = $_POST['message'];
$phone= $_POST['mob'];
$subject = "contact";
$subject2 = "Copy of your form submission";
$message = "Name:-" . $first_name . "\n\n" . "Email:-" . $mail . "\n\n" . "Phone Number:- " .$phone . "\n\n" . " Message:- " . $msg;
$headers = "From:" . $from;
$headers .= " MIME-Version: 1.0\r\n"; #Define MIME Version
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n"; #Set content type
mail($to,$subject,$message,$headers);
header('Location: thank-you.php');
}
else{
echo 'Your message cannot be sent.';
}
?>
I have the php code working up to the point where I need the image to get attached to a variable and i gets emailed with the rest of my form. I get 2 errors. One error is telling me that $messageImage in undefined on line 75? and the other is: Call to a member function addAttachment() on a non-object on line 75.
can someone explain the proper way of declaring the variable and making sure it is an object so that addAttachment works. Thank You
//copy the temp. uploaded file to uploads folder
$upload_folder = 'uploads/';
$path_of_uploaded_file = $upload_folder . $name_of_uploaded_file;
$tmp_path = $_FILES["uploaded_file"]["tmp_name"];
if(is_uploaded_file($tmp_path)) {
if(!copy($tmp_path,$path_of_uploaded_file))
{
$errors = '\n error while copying the uploaded file';
}
}
$to = "example#gmail.com"; // this is your Email address
$from = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL); // this is the sender's Email address
$first_name = filter_var($_POST['first_name'], FILTER_SANITIZE_STRING);
$story = filter_var($_POST['message'], FILTER_SANITIZE_STRING);
$subject = "subject";
$subject2 = "Thank You for submitting";
$messageImage->addAttachment($path_of_uploaded_file);
$message = $first_name . " wrote the following:" . "\n\n" . $story;
$message2 = "Here is a copy of your story " . $first_name . "\n\n" . $story;
$headers = "From:" . $from;
$headers2 = "From:" . $to;
mail($to,$subject,$message,$messageImage,$headers);
mail($from,$subject2,$message2,$headers2); // sends a copy of the message to the sender
'$messageImage' is an object in your code and it is not define.
You can check this with simple if check like below,
if ($messageImage) {
// do something
}
Following code can work for you,
//copy the temp. uploaded file to uploads folder
$upload_folder = 'uploads/';
$to = "example#gmail.com"; // this is your Email address
$from = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL); // this is the sender's Email address
$first_name = filter_var($_POST['first_name'], FILTER_SANITIZE_STRING);
$story = filter_var($_POST['message'], FILTER_SANITIZE_STRING);
$subject = "subject";
$subject2 = "Thank You for submitting";
$message = $first_name . " wrote the following:" . "\n\n" . $story;
$message2 = "Here is a copy of your story " . $first_name . "\n\n" . $story;
$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";
$content = '';
$tmp_path = $_FILES["uploaded_file"]["tmp_name"];
if($tmp_path) {
$filename = $_FILES["uploaded_file"]["name"];
$path_of_uploaded_file = $upload_folder . $filename;
if(!copy($tmp_path, $path_of_uploaded_file))
{
$errors = '\n error while copying the uploaded file';
}
$file_size = filesize($path_of_uploaded_file);
$handle = fopen($path_of_uploaded_file, "rb");
$content = fread($handle, $file_size);
fclose($handle);
$content = chunk_split(base64_encode($content));
}
// if attachment
if ($content) {
$message .= "Content-Type: {\"application/octet-stream\"};\n" . " name=\"{$filename}\"\n" .
"Content-Disposition: attachment;\n" . " filename=\"{$filename}\"\n" .
"Content-Transfer-Encoding: base64\n\n" . $content . "\n\n";
$message .= "--{$mime_boundary}\n";
}
$headers2 = "From:" . $to;
mail($to, $subject, $message, $headers);
mail($from, $subject2, $message2, $headers2); // sends a copy of the message to the sender
In your code, $messageImage is not being set. Since it is not set, it is NULL, causing the next error, you are trying to refer to the method of an object, but it is null.
To send a message with attachments, you need to set email headers, and the image is base64 encoded in the message. I would look at this other StackOverflow answer:
https://stackoverflow.com/a/17371739/2832264
To make a simple object:
$obj = new stdClass();
Otherwise, you would create a class, make sure it is included in your script, and create a new instance of that:
$obj = new Person();
I would read the official PHP documentation on classes.
I built a form for my website using php. After the form is submitted, the content is emailed to me and the user is redirected to a different page. The code works fine when I fill the form out completely. However, one of the fields is a file upload and when I don't upload anything, the form still sends but leads to a 500 internal server error page. How can I make it so the form still redirects to the right page when a file isn't uploaded? I included my code below
<?php
$email_to = "ashley#MyURL.com";
$email_subject = "Completed Questionnaire";
$name = $_POST['name'];
$gradyear = $_POST['gradyear'];
$hschool = $_POST['hschool'];
$hometown = $_POST['hometown'];
$email_from = $_POST['email'];
$DOB = $_POST['DOB'];
$GPA = $_POST['GPA'];
$height = $_POST['height'];
$weight = $_POST['weight'];
$about = $_POST['about'];
$message = "Form details below.\n\n";
function clean_string($string) {
$bad = array("content-type","bcc:","to:","cc:","href");
return str_replace($bad,"",$string);}
$message .= "Name: ".clean_string($name)."\n";
$message .= "Graduation Year: ".clean_string($gradyear)."\n";
$message .= "High School: ".clean_string($hschool)."\n";
$message .= "Hometown: ".clean_string($hometown)."\n";
$message .= "Email: ".clean_string($email_from)."\n";
$message .= "Date of Birth: ".clean_string($DOB)."\n";
$message .= "GPA: ".clean_string($GPA)."\n";
$message .= "Height: ".clean_string($height)."\n";
$message .= "Weight: ".clean_string($weight)."\n";
$message .= "About: ".clean_string($about)."\n";
/* GET File Variables */
$tmpName = $_FILES['attachment']['tmp_name'];
$fileType = $_FILES['attachment']['type'];
$fileName = $_FILES['attachment']['name'];
/* Start of headers */
$headers = "From: $email_from";
if (file($tmpName)) {
/* Reading file ('rb' = read binary) */
$file = fopen($tmpName,'rb');
$data = fread($file,filesize($tmpName));
fclose($file);
/* a boundary string */
$randomVal = md5(time());
$mimeBoundary = "==Multipart_Boundary_x{$randomVal}x";
/* Header for File Attachment */
$headers .= "\nMIME-Version: 1.0\n";
$headers .= "Content-Type: multipart/mixed;\n" ;
$headers .= " boundary=\"{$mimeBoundary}\"";
/* Multipart Boundary above message */
$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" .
$message . "\n\n";
/* Encoding file data */
$data = chunk_split(base64_encode($data));
/* Adding attchment-file to message*/
$message .= "--{$mimeBoundary}\n" .
"Content-Type: {$fileType};\n" .
" name=\"{$fileName}\"\n" .
"Content-Transfer-Encoding: base64\n\n" .
$data . "\n\n" .
"--{$mimeBoundary}--\n";
}
#mail($email_to, $email_subject, $message, $headers);
header("Location: http://myURL.com/contact.html");
?>
You should check first that a file was indeed uploaded before manipulating the file:
if ( ! empty($_FILES)) {
//file manipulation...
}
thank you for looking at this. I am quite new to the PHP coding side. So basically I have pieced together a form it works. But I want to have the file upload option... well optional. I've read over many questions/sites but I can't seem to figure it out. So I've come here. I'll post the code below. I'd really like to stick to this code and not have to redo the whole form, for now.
<?php
$fnameErr = $lnameErr = $emailErr = $phoneErr = "";
$fname = $lname = $email = $phone = "";
if ($_SERVER['REQUEST_METHOD'] == "POST"){
$webMaster="email#email.com"; //email removed on purpose for upload//
$subject="Online Price Request";
$from = stripslashes($_POST['fname'])." ".stripslashes($_POST['lname'])."<".stripslashes($_POST['email']).">";
if (empty($_POST["fname"]))
{$fnameErr = "First name is required";}
else
{
if (!preg_match("/^[a-zA-Z ]*$/",$fname))
{
$fnameErr = "Only letters allowed";
}
}
if (empty($_POST["lname"]))
{$lnameErr = "Last name is required";}
else
{
if (!preg_match("/^[a-zA-Z ]*$/",$lname))
{
$lnameErr = "Only letters allowed";
}
}
if (empty($_POST["email"]))
{$emailErr = "Email is required";}
if (empty($_POST["phone"]))
{$phoneErr = "Phone number is required";}
else
{
if (!preg_match("/^[-0-9 ]*$/",$phone))
{
$phoneErr = "Only numbers are allowed"; }?>
<?php
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$dateevent = $_POST['dateevent'];
$garmenttype = $_POST['garmenttype'];
$garmentquantity = $_POST['garmentquantity'];
$garmentsize = $_POST['garmentsize'];
$garmentcolor = $_POST['garmentcolor'];
$garmentstyle = $_POST['garmentstyle']; $imprint1 = $_POST['imprint1'];
$imprint2 = $_POST['imprint2'];
$artworkyes = $_POST['artworkyes'];
$artworkno = $_POST['artworkno'];
$artwork = $_POST['artwork'];
$artworkfile = $_POST['artworkfile'];
$info = $_POST['info'];
}
$mime_boundary="==Multipart_Boundary_x".md5(mt_rand())."x";
$tmp_name = $_FILES['artworkfile']['tmp_name'];
$type = $_FILES['artworkfile']['type'];
$file_name = $_FILES['artworkfile']['name'];
$size = $_FILES['artworkfile']['size'];
$body = "\n\n First Name: $fname \n\n Last Name: $lname \n\n Phone: $phone \n\n Date of Event: $dateevent \n\n Garment Type: $garmenttype \n\n Garment Style (Numeric): $garmentstyle \n\n Amount of Garment: $garmentquantity \n\n Color of Garment: $garmentcolor \n\n Front Colors: $imprint1 \n\n Back Colors: $imprint2 \n\n Artwork: $artwork \n\n Uploaded Artwork: $file_name \n\n Additional Information: $info";
if (file_exists($tmp_name)){
if(is_uploaded_file($tmp_name)){
$file = fopen($tmp_name,'rb');
$data = fread($file,filesize($tmp_name));
fclose($file);
$data = chunk_split(base64_encode($data));
}
$headers = "From: $from\r\n" .
"MIME-Version: 1.0\r\n" .
"Content-Type: multipart/mixed;\r\n" .
" boundary=\"{$mime_boundary}\"";
$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" .
"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";
if (#mail($webMaster, $subject, $body, $headers))
{ ?>
<div><center><h1>Request Sent Successfully !!</h1></center></div>
<div><center><h2>Click here to return to the main page.</h2></center></div>
<?php
}else
{
?>
<div><center>
<h1>Error !! Unable to send Request...</h1></center></div>
<?php }}} ?>
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
}
?>