After submitting the form it shows
"Your Data Has been submitted we will contact you soon !!"
at the same time, the form inputs fields remains in the Page(Still submiited data exist on the fields)
How can I clear the data in input fields after submitted
Here is my code :
<?php
if(isset($_POST['name']))
{
include_once("config.php");
$name=$email=$phone=$uploadresume="";
$nameErr=$emailErr=$phoneErr=$uploadresumeErr="";
function test_input($data)
{
$data=trim($data);
$data=stripslashes($data);
$data=htmlspecialchars($data);
return $data;
}
if ($_SERVER['REQUEST_METHOD']=="POST"){
$valid=true;
//name validaton
if(empty($_POST["name"]))
{
$nameErr="* Name is Required";
$valid=false;
}
else
{
$name=test_input($_POST["name"]);
if (!preg_match("/^[a-zA-Z ]*$/",$name))
{
$nameErr = " Only letters and white space allowed";
$valid=false;
}
}
//Email Address validaton
if(empty($_POST["email"]))
{
$emailErr="* Email is Required";
$valid=false;
}
else
{
$email=test_input($_POST["email"]);
if (!preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/",$email))
{
$emailErr=" Enter a valid Email ID";
$valid=false;
}
}
//Mobile no validaton
if(empty($_POST["phone"]))
{
$phoneErr="* Mobile no is Required";
$valid=false;
}
else
{
$phone=test_input($_POST["phone"]);
if(!preg_match("/^(\d[\s-]?)?[\(\[\s-]{0,2}?\d{3}[\)\]\s-]{0,2}?\d{3}[\s-]?\d{4}$/i",$phone))
{
$phoneErr="*Enter a valid contact no";
$valid=false;
}
}
if(empty($_FILES["filename"]['name']))
{
$uploadresumeErr="* Upload Your Resume";
$valid=false;
}
else
{
$fname_arr = explode('.',$_FILES["filename"]['name']);
$fileext = $fname_arr[count($fname_arr)-1];
$ext_arr = array('doc','pdf');
if(in_array($fileext,$ext_arr))
{
$uploadresume=test_input($_POST["filename"]);
}
else{
$uploadresumeErr="* Upload only doc or pdf files.";
$valid=false;
}
}
if($valid)
{
// Add user info into the database table, claim your fields then values
$sql = mysql_query("INSERT INTO jobopening(name, email, phone,applieddate,Appliedjob)
VALUES('$_POST[name]','$_POST[email]','$_POST[phone]', now(),'dataentry')") or die (mysql_error());
// Get the inserted ID here to use in the activation email
$id = mysql_insert_id();
$to = "example#example.co.in";
// Change this to your site admin email
$from = "$_POST[email]";
$subject = "Applied for DataEntry FROM $_POST[name] ";
//Begin HTML Email Message where you need to change the activation URL inside
// Get all the values from input
$name = $_POST['name'];
$email_address = $_POST['email'];
$phone = $_POST['phone'];
// Now Generate a random string to be used as the boundary marker
$mime_boundary="==Multipart_Boundary_x".md5(mt_rand())."x";
// Now Store the file information to a variables for easier access
$tmp_name = $_FILES['filename']['tmp_name'];
$type = $_FILES['filename']['type'];
$file_name = $_FILES['filename']['name'];
$size = $_FILES['filename']['size'];
// Now here we setting up the message of the mail
$message = "
\n\n Applied For DataEntry
\n\n Name: $name
\n\n Email: $email_address
\n\n Phone: $phone";
// Check 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)){
// 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}\"";
// Next, we'll build the message body note that we insert two dashes in front of the MIME boundary when we use it
$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";
// 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";
// Thats all.. Now we need to send this mail... :)
if (#mail($to, $subject, $message, $headers))
{
?>
<div><center><h1>Your Data Has been submitted we will contact you soon !!</h1></center></div>
<?php
}else
{
?>
<div>
<center>
<h1>Error !! Unable to send yor data..</h1>
</center>
</div>
<?php
}
}
}
}
}
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" enctype="multipart/form-data">
<label>Name:</label>
<input type="text" name="name" value="<?php echo $_POST["name"]?>"/>
<?php echo $nameErr?> <br />
<br />
<label>Email-ID:</label>
<input type="text" name="email" value="<?php echo $_POST["email"]?>"/>
<?php echo $emailErr?> <br />
<br />
<label>Phone No:</label>
<input type="text" name="phone" value="<?php echo $_POST["phone"]?>"/>
<?php echo $phoneErr?> <br />
<br />
<label for="tele">upload Resume</label>
<input type="file" name="filename" id="tele"/>
<?php echo $uploadresumeErr?> <br />
<br />
<input style="display:block; margin-left:35em;"type="submit" value="Submit"/>
</form>
Store $_POST in a variable inside
if(isset($_POST['name']))
{
$post_val=$_POST;
---------
Then,Unset $post_val after sending email
if (#mail($to, $subject, $message, $headers))
{
unset($post_val);
?>
Show the values from $_post_val
<input type="text" name="name" value="<?php echo $_post_val["name"]?>"/>
<input type="text" name="email" value="<?php echo $_post_val["email"]?>"/>
<input type="text" name="phone" value="<?php echo $_post_val["phone"]?>"/>
You are setting the value of the fields using the $_POST variable. Once the form is submitted the $_POST array gets populated. So when the page is loaded after submitting , the values of the inputs are set. You need to remove them.
Change
<input type="text" name="name" value="<?php echo $_POST["name"]?>"/>
<input type="text" name="email" value="<?php echo $_POST["email"]?>"/>
<input type="text" name="phone" value="<?php echo $_POST["phone"]?>"/>
to
<input type="text" name="name" value=""/>
<input type="text" name="email" value=""/>
<input type="text" name="phone" value=""/>
After Inserting data into data base and sending email, You should Redirect to the same page
header("location:".$_SERVER['PHP_SELF']);
Related
I have been trying to create a html form for users to send a mail with an attachment using the php mail function. The mail gets sent successfully but without the attachment. When i tried to check the file being uploaded I don't seem to be getting the file selected by the user. Below is my html code
<form name="message" id="message" method="post" action="mail.php" enctype="multipart/form-data">
<input type="text" class ="text-class" id="name" name="name" placeholder="Name*" required/>
<input type="email" class ="text-class" placeholder="Email*" name="Email" id ="Email" required/>
<textarea class ="text-class" placeholder="Message*" name="Message" id="Message" required></textarea>
<div class="captcha">
<div class="row">
<div class="4u">
<input class ="text-class" type="text" value="2 + 3 is ?" name="question" readonly/>
</div>
<div class="8u">
<input class ="text-class" type="text" placeholder="Answer*" name="captcha" id="captcha" required/>
</div>
</div>
</div>
<input type="hidden" name="MAX_FILE_SIZE" value="30000" />
<input type="file" name="attachment" id="attachment"/>
<input type="submit" name="Submit" value="Send" class="submit"/>
</form>
mail.php
<?php
if(isset($_POST['Submit']) && ($_POST['Submit']) == 'Send' )
{
// Checking For Blank Fields..
if($_POST["name"]==""||$_POST["Email"]==""||$_POST["Message"]==""){
echo "Fill All Fields..";
}else{
// Check if the "Sender's Email" input field is filled out
$email=$_POST['Email'];
// Sanitize E-mail Address
$email =filter_var($email, FILTER_SANITIZE_EMAIL);
// Validate E-mail Address
$email= filter_var($email, FILTER_VALIDATE_EMAIL);
if (!$email){
echo "Invalid Sender's Email";
}
else{
$message = $_POST['Message'];
$headers = 'From:'. $email . "\r\n"; // Sender's Email
/* GET File Variables */
$tmpName = $_FILES['attachment']['tmp_name'];
$fileType = $_FILES['attachment']['type'];
$fileName = $_FILES['attachment']['name'];
if((empty($_POST['attachment'])) || (empty($_FILES['attachment']))){
echo "No attachement!";
}
else{
//file is attached, process it and send via mail
$file = fopen($tmpName,'rb');
$data = fread($file,filesize($tmpName));
fclose($file);
$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("mail#test.com", "Mail from my website", $message, $headers);
echo "Your message has been received by us ! Thank you for contacting us";
echo "<script>
alert('Your message has been sent!');
</script>";
}
exit;
}
}
}else{
echo "Not submitted";
}
?>
I get "No attachment" messaged echoed since I don't seem to be getting the selected file from the html form. Please can someone tell me where I'm going wrong?
In the below code i have validation for all fields
Without validation in upload resume i can upload the file
Validations are working but i can't upload the file
may i know how to do validation in upload file:
<?php
if(isset($_POST['name']))
{
$name=$email=$phone=$uploadresume="";
$nameErr=$emailErr=$phoneErr=$uploadresumeErr="";
function test_input($data)
{
$data=trim($data);
$data=stripslashes($data);
$data=htmlspecialchars($data);
return $data;
}
if ($_SERVER['REQUEST_METHOD']=="POST"){
$valid=true;
//name validaton
if(empty($_POST["name"]))
{
$nameErr="* Name is Required";
$valid=false;
}
else
{
$name=test_input($_POST["name"]);
if (!preg_match("/^[a-zA-Z ]*$/",$name))
{
$nameErr = " Only letters and white space allowed";
$valid=false;
}
}
//Email Address validaton
if(empty($_POST["email"]))
{
$emailErr="* Email is Required";
$valid=false;
}
else
{
$email=test_input($_POST["email"]);
if (!preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/",$email))
{
$emailErr=" Enter a valid Email ID";
$valid=false;
}
}
//Mobile no validaton
if(empty($_POST["phone"]))
{
$phoneErr="* Mobile no is Required";
$valid=false;
}
else
{
$phone=test_input($_POST["phone"]);
if(!preg_match("/^(\d[\s-]?)?[\(\[\s-]{0,2}?\d{3}[\)\]\s-]{0,2}?\d{3}[\s-]?\d{4}$/i",$phone))
{
$phoneErr="*Enter a valid contact no";
$valid=false;
}
}
if(empty($_POST["filename"]))
{
$uploadresumeErr="* Upload Your Resume";
$valid=false;
}
else
{
$uploadresume=test_input($_POST["filename"]);
}
if($valid)
{
$to = "example#example.co.in";
// Change this to your site admin email
$from = "$_POST[email]";
$subject = "Applied for DataEntry FROM $_POST[name] ";
//Begin HTML Email Message where you need to change the activation URL inside
// Get all the values from input
$name = $_POST['name'];
$email_address = $_POST['email'];
$phone = $_POST['phone'];
// Now Generate a random string to be used as the boundary marker
$mime_boundary="==Multipart_Boundary_x".md5(mt_rand())."x";
// Now Store the file information to a variables for easier access
$tmp_name = $_FILES['filename']['tmp_name'];
$type = $_FILES['filename']['type'];
$file_name = $_FILES['filename']['name'];
$size = $_FILES['filename']['size'];
// Now here we setting up the message of the mail
$message = "
\n\n Applied For DataEntry
\n\n Name: $name
\n\n Email: $email_address
\n\n Phone: $phone";
// Check 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)){
// 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}\"";
// Next, we'll build the message body note that we insert two dashes in front of the MIME boundary when we use it
$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";
// 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";
// Thats all.. Now we need to send this mail... :)
if (#mail($to, $subject, $message, $headers))
{
?>
<div>
<center>
<h1>Your Data Has been submitted we will contact you soon !!</h1>
</center>
</div>
<?php
}else
{
?>
<div>
<center>
<h1>Error !! Unable to send yor data..</h1>
</center>
</div>
<?php
}
}
}
}
}
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" enctype="multipart/form-data">
<label>Name:</label>
<input type="text" name="name" value="<?php echo $_POST["name"]?>"/><?php echo $nameErr?>
<br />
<br />
<label>Email-ID:</label>
<input type="text" name="email" value="<?php echo $_POST["email"]?>"/><?php echo $emailErr?>
<br />
<br />
<label>Phone No:</label>
<input type="text" name="phone" value="<?php echo $_POST["phone"]?>"/><?php echo $phoneErr?>
<br />
<br />
<label for="tele">upload Resume</label>
<input type="file" name="filename" id="tele"/><?php echo $uploadresumeErr?>
<br /><br />
<input style="display:block; margin-left:35em;"type="submit" value="Submit"/>
</form>
For validation of file use the below code :
if(empty($_FILES["filename"]['name']))
{
$uploadresumeErr="* Upload Your Resume";
$valid=false;
}
else
{
$uploadresume=test_input($_POST["filename"]);
}
In the below code its is uploading all file type but i need only doc and pdf file
i want to upload only doc and pdf file help me friends may i know how to do that
tomorrow is my project submission i donn't know what to do help me friends
i'm getting code from other sites but i couldn't understand anything
<?php
if(isset($_POST['name']))
{
$name=$email=$phone=$uploadresume="";
$nameErr=$emailErr=$phoneErr=$uploadresumeErr="";
function test_input($data)
{
$data=trim($data);
$data=stripslashes($data);
$data=htmlspecialchars($data);
return $data;
}
if ($_SERVER['REQUEST_METHOD']=="POST"){
$valid=true;
//name validaton
if(empty($_POST["name"]))
{
$nameErr="* Name is Required";
$valid=false;
}
else
{
$name=test_input($_POST["name"]);
if (!preg_match("/^[a-zA-Z ]*$/",$name))
{
$nameErr = " Only letters and white space allowed";
$valid=false;
}
}
//Email Address validaton
if(empty($_POST["email"]))
{
$emailErr="* Email is Required";
$valid=false;
}
else
{
$email=test_input($_POST["email"]);
if (!preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/",$email))
{
$emailErr=" Enter a valid Email ID";
$valid=false;
}
}
//Mobile no validaton
if(empty($_POST["phone"]))
{
$phoneErr="* Mobile no is Required";
$valid=false;
}
else
{
$phone=test_input($_POST["phone"]);
if(!preg_match("/^(\d[\s-]?)?[\(\[\s-]{0,2}?\d{3}[\)\]\s-]{0,2}?\d{3}[\s-]?\d{4}$/i",$phone))
{
$phoneErr="*Enter a valid contact no";
$valid=false;
}
}
if(empty($_FILES["filename"]['name']))
{
$uploadresumeErr="* Upload Your Resume";
$valid=false;
}
else
{
$uploadresume=test_input($_POST["filename"]);
}
if($valid)
{
$to = "example#example.co.in";
// Change this to your site admin email
$from = "$_POST[email]";
$subject = "Applied for DataEntry FROM $_POST[name] ";
//Begin HTML Email Message where you need to change the activation URL inside
// Get all the values from input
$name = $_POST['name'];
$email_address = $_POST['email'];
$phone = $_POST['phone'];
// Now Generate a random string to be used as the boundary marker
$mime_boundary="==Multipart_Boundary_x".md5(mt_rand())."x";
// Now Store the file information to a variables for easier access
$tmp_name = $_FILES['filename']['tmp_name'];
$type = $_FILES['filename']['type'];
$file_name = $_FILES['filename']['name'];
$size = $_FILES['filename']['size'];
// Now here we setting up the message of the mail
$message = "
\n\n Applied For DataEntry
\n\n Name: $name
\n\n Email: $email_address
\n\n Phone: $phone";
// Check 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)){
// 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}\"";
// Next, we'll build the message body note that we insert two dashes in front of the MIME boundary when we use it
$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";
// 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";
// Thats all.. Now we need to send this mail... :)
if (#mail($to, $subject, $message, $headers))
{
?>
<div>
<center>
<h1>Your Data Has been submitted we will contact you soon !!</h1>
</center>
</div>
<?php
}else
{
?>
<div>
<center>
<h1>Error !! Unable to send yor data..</h1>
</center>
</div>
<?php
}
}
}
}
}
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" enctype="multipart/form-data">
<label>Name:</label>
<input type="text" name="name" value="<?php echo $_POST["name"]?>"/>
<?php echo $nameErr?> <br />
<br />
<label>Email-ID:</label>
<input type="text" name="email" value="<?php echo $_POST["email"]?>"/>
<?php echo $emailErr?> <br />
<br />
<label>Phone No:</label>
<input type="text" name="phone" value="<?php echo $_POST["phone"]?>"/>
<?php echo $phoneErr?> <br />
<br />
<label for="tele">upload Resume</label>
<input type="file" name="filename" id="tele"/>
<?php echo $uploadresumeErr?> <br />
<br />
<input style="display:block; margin-left:35em;"type="submit" value="Submit"/>
</form>
You should check the MIME type of the file that was uploaded and then do a check if the allowed type is there or not.
Checking the MIME type..
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mimetype = finfo_file($finfo, $_FILES['file']['tmp_name']);
echo $mimetype;
Your $allowedrules array
$allowedrules = array(
'application/msword',
'text/pdf',
);
You must do a check if your $mimetype exists on this array. If it is there, then it is a legit upload.
I am an eager novice with PHP so please forgive my errors as I am learning as I go. Basically, I am building a simple contact form for my website and have successfully been able to have the form send the user's first and last name, subject, email address and message. I am using a second file, "form_process.php" to process the form data from "index.php".
The problem is that the email address does not seem to be validating and will send any words typed. I would greatly appreciate it if some more seasoned eyes could take a look and help me sort this out. Thank you in advance.
Michael.
HTML:
<div id="form">
<form action="form_process.php" method="post" enctype="multipart/form-data">
<p>
<input type="text" maxlength="100" size="50" name="fName" value="<?php echo $stored_fName;?>" placeholder="First Name" />
</p>
<p>
<input type="text" maxlength="100" size="50" name="lName" value="<?php echo $stored_lName;?>" placeholder="Last Name" />
</p>
<p>
<input type="text" maxlength="80" size="50" name="email" value="<?php echo $stored_email;?>" placeholder="Email Address" />
</p>
<p>
<input type="text" maxlength="100" size="50" name="subject" value="<?php echo $stored_subject;?>" placeholder="Subject" />
</p>
<p>
<textarea name="message" rows="6" cols="38" placeholder="Message"></textarea>
</p>
<br />
<input type="submit" value="Submit" name="submit" />
<input type="reset" value="Clear" name="clear">
</form>
</div>
<!-- form ends -->
PHP: "form_process.php"
<?php
session_start();
// Report all PHP errors
error_reporting(E_ALL);
//use $_POST to to store data from submitted form into these variables
$fName = check_input($_POST['fName']);
$lName = check_input($_POST['lName']);
$sender = check_input($_POST['email']);
$subject = check_input($_POST['subject']);
$message = check_input($_POST['message']);
//check_input function to strip unnessessary characters and sanitize user data
function check_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
$name = $fName ." ". $lName;//concatenating first and last names to new name variable
$sanitizedEmail = filter_var($sender, FILTER_SANITIZE_EMAIL);
//generates error messages on index.php if form fields left blank
if ($fName == ''){
header("Location:index.php?message=1");
exit();
}
if ($lName == ''){
header("Location:index.php?message=2");
exit();
}
if ($sender == ''){
header("Location:index.php?message=3");
exit();
}
if ($subject == ''){
header("Location:index.php?message=4");
exit();
}
if ($message == ''){
header("Location:index.php?message=5");
exit();
}
//headers
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=iso-8859-1" . "\r\n";
$headers .= $name . "\r\n";
$headers .= "From:" . " " . $sanitizedEmail . "\r\n";
//mail function
$to = "me#myemail.com";
$subject = $subject;
$message = $message;
//send message
$send_message = mail($to,$subject,$message,$headers);
if($send_message){
header("Location:index.php?message=6");
}else {
header("Location:index.php?message=9");
exit();
}
?>
"index.php" error messages:
<?php
//all fields empty until user inputs data for session to store
$stored_fName = '';//init as NULL
$stored_lName = '';//init as NULL
$stored_email = '';//init as NULL
$stored_subject = '';//init as NULL
$stored_message = '';//init as NULL
//session data used to repopulate form fields if any info is missing or incorrect
if (isset($_SESSION['fName'])){
$stored_fName = $_SESSION['fName'];
}
if (isset($_SESSION['lName'])){
$stored_lName = $_SESSION['lName'];
}
if (isset($_SESSION['email'])){
$stored_email = $_SESSION['email'];
}
if (isset($_SESSION['subject'])){
$stored_subject = $_SESSION['subject'];
}
if (isset($_SESSION['message'])){
$stored_message = $_SESSION['message'];
}
//error messages displayed to user if text fields have been left blank
$_GET['message'];
if ($_GET['message'] == 1) {//first name
echo "<strong>Please type your first name.</strong>";
}
if ($_GET['message'] == 2) {//last name
echo "<strong>Please type your last name.</strong>";
}
if ($_GET['message'] == 3){//email address
echo "<strong>Please type an email address.</strong>";
}
if ($_GET['message'] == 4){//subject
echo "<strong>Please type a subject.</strong>";
}
if ($_GET['message'] == 5){//message text
echo "<strong>Please type your message.</strong>";
}
if ($_GET['message'] == 6){//message success from form_process.php
echo "<strong>Your message was sent successfully. Thank you.</strong>";
}
if ($_GET['message'] == 9){
echo "<strong>I'm sorry but your message was not sent. Please try again, thank you.</strong>";
}
?>
You should be using it like this:
if(filter_var($email, FILTER_VALIDATE_EMAIL)){
// is email
$sender = $email;
}else{
// isn't email
$sender = '';
}
Read more about PHP Validate Filters
So i have this contact form, everything sends fine after the submit button is pressed. However the confirmation email does not seem to send...
I couldnt find the answer on here anywhere, or i would not have asked
The Confirmation email code
<?php
$your_email = "jp.vaughan#icloud.com"; // email address to which the form data will be sent
$subject = "Contact Email";
$thanks_page = "/contact/thankyou.html";
if (isset($_POST["submit"])) {
$nam = $_POST["name"];
$ema = trim($_POST["email"]);
$org = trim($_POST["organisation"]);
$com = $_POST["comments"];
$loadtime = $_POST["loadtime"];
if (get_magic_quotes_gpc()) {
$nam = stripslashes($nam);
$ema = stripslashes($ema);
$org = stripslashes($org);
$com = stripslashes($com);
}
$error_msg=array();
if (empty($nam) || !preg_match("~^[a-z\-'\s]{1,60}$~i", $nam)) {
$error_msg[] = "The name field must contain only letters, spaces, dashes ( - ) and single quotes ( ' )";
}
if (empty($ema) || !filter_var($ema, FILTER_VALIDATE_EMAIL)) {
$error_msg[] = "Your email must have a valid format, such as name#mailhost.com";
}
if (empty($org) || !preg_match("~^[a-z\-'\s]{1,60}$~i", $org)) {
$error_msg[] = "The Organisation must contain only letters, spaces, dashes ( - ) and single quotes ( ' )";
}
$limit = 1000000000000000000000000000000000000;
if (empty($com) || !preg_match("/^[0-9A-Za-z\/-\s'\(\)!\?\.,]+$/", $com) || (strlen($com) > $limit)) {
$error_msg[] = "Your message must contain only letters, digits, spaces and basic punctuation ( ' - , . )";
}
$totaltime = time() - $loadtime;
if($totaltime < 7) {
echo("<p>Please fill in the form before submitting!</p>");
echo '</ul>
<form method="post" action="', $_SERVER['PHP_SELF'], '">
<input placeholder="Your Name*" name="name" type="text" id="name" value="'; if (isset($_POST["name"])) {echo $nam;}; echo '">
<input placeholder="Your Email Address*" name="email" type="email" id="email"'; if (isset($_POST["email"])) {echo $ema;}; echo '">
<input placeholder="Your Organisation*" name="organisation" type="text" id="organisation" value="'; if (isset($_POST["organisation"])) {echo $org;}; echo '">
<textarea placeholder="Your Message" name="comments" rows="5" cols="50" id="comm">'; if (isset($_POST["comments"])) {echo $com;}; echo '</textarea>
<input type="hidden" name="loadtime" value="', time(), '">
<input type="submit" name="submit" value=" SEND" id="submit">
</form>';
exit;
}
if ($error_msg) {
echo '
<p>Unfortunately, your message could not be sent. The form as you filled it out is displayed below. Make sure each field is completed. Please address any issues listed below:</p>
<ul class="err">';
foreach ($error_msg as $err) {
echo '<li>'.$err.'</li>';
}
echo '</ul>
<form method="post" action="', $_SERVER['PHP_SELF'], '">
<input placeholder="Your Name*" name="name" type="text" id="name" value="'; if (isset($_POST["name"])) {echo $nam;}; echo '">
<input placeholder="Your Email Address*" name="email" type="email" id="email"'; if (isset($_POST["email"])) {echo $ema;}; echo '">
<input placeholder="Your Organisation*" name="organisation" type="text" id="organisation" value="'; if (isset($_POST["organisation"])) {echo $org;}; echo '">
<textarea placeholder="Your Message" name="comments" rows="5" cols="50" id="comm">'; if (isset($_POST["comments"])) {echo $com;}; echo '</textarea>
<input type="hidden" name="loadtime" value="', time(), '">
<input type="submit" name="submit" value=" SEND" id="submit">
</form>';
exit();
}
$email_body =
"Name of sender: $nam\n\n" .
"Email of sender: $ema\n\n" .
"Organisaition: $org\n\n" .
"COMMENTS:\n\n" .
"$com" ;
if (!$error_msg) {
mail ($your_email, $subject, $email_body, "From: $nam <$ema>" . "\r\n" . "Reply-To: $nam <$ema>");
die ("Thank you. Your message has been sent to the appropriate person.");
exit();
}
$sendto = $_POST["email"]; // this is the email address collected form the form
$ccto = "jp.vaughan#icloud.com"; //you can cc it to yourself
$subjectCon = "Email Confirmation"; // Subject
$message = "the body of the email - this email is to confirm etc...";
$header = "From: auto-confirm#moibrahimfoundation.org\r\n";
// This is the function to send the email
if(isset($_POST['submit'])) {
mail($sendto, $subjectCon, $message, $header);
}}
?>
you are exiting the code after sending the first email.
if (!$error_msg) {
if (mail ($your_email, $subject, $email_body, "From: $nam <$ema>" . "\r\n" . "Reply-To: $nam <$ema>");
die ("Thank you. Your message has been sent to the appropriate person."); //you are exiting here
exit(); //additional exit here. the second email won't be sent if there is no error.
}
$sendto = $_POST["email"]; // this is the email address collected form the form
$ccto = "jp.vaughan#icloud.com"; //you can cc it to yourself
$subjectCon = "Email Confirmation"; // Subject
$message = "the body of the email - this email is to confirm etc...";
$header = "From: auto-confirm#moibrahimfoundation.org\r\n";
// This is the function to send the email
if(isset($_POST['submit'])) {
mail($sendto, $subjectCon, $message, $header);
should be
$success='';
if (!$error_msg) {
if (mail ($your_email, $subject, $email_body, "From: $nam <$ema>" . "\r\n" . "Reply-To: $nam <$ema>")){
$success="Thank you. Your message has been sent to the appropriate person.";
}else{
$success="Your message cannot be sent";
}
}
$sendto = $_POST["email"]; // this is the email address collected form the form
$ccto = "jp.vaughan#icloud.com"; //you can cc it to yourself
$subjectCon = "Email Confirmation"; // Subject
$message = "the body of the email - this email is to confirm etc...";
$header = "From: auto-confirm#moibrahimfoundation.org\r\n";
// This is the function to send the email
if(isset($_POST['submit'])) {
mail($sendto, $subjectCon, $message, $header);
die($success);
if your first mail is also not sending please check the mail configuration in your php.ini and verify that you can send mail through it.
use this tool for checking ur mail is sending or not...also it will show all parameters of mail function...
Test Tool