Simple PHP result message with some other points - php

Html Code (index.html)
<div id="stable" class="center-div" >
<form method="POST" action="send.php">
<input type="text" name="FNAME" value="FIRST NAME" size="20" onfocus="if(this.value==this.defaultValue)this.value='';" onblur="if(this.value=='')this.value=this.defaultValue;">
<!--<input type="text" name="LNAME" value="LAST NAME" size="20" onfocus="if(this.value==this.defaultValue)this.value='';" onblur="if(this.value=='')this.value=this.defaultValue;">-->
<input type="text" name="Email" VALUE="EMAIL" size="20" style="font-size:13px; height:50px; background-color:#f5f5f5"onfocus="if(this.value==this.defaultValue)this.value='';" onblur="if(this.value=='')this.value=this.defaultValue;">
<input type="submit" value="Submit" name="Submit" class="button">
</div>
</form>
Php code (send.php)
<?php
## CONFIG ##
# LIST EMAIL ADDRESS
$recipient = "admin#gmail.com";
# SUBJECT (Subscribe/Remove)
$subject = "Someone wants updates!";
# RESULT PAGE
$location = "index.html";
## FORM VALUES ##
# SENDER - WE ALSO USE THE RECIPIENT AS SENDER IN THIS SAMPLE
# DON'T INCLUDE UNFILTERED USER INPUT IN THE MAIL HEADER!S
$sender = $recipient;
# MAIL BODY
$body .= "Name: ".$_REQUEST['FNAME']." \n";
$body .= "Email: ".$_REQUEST['Email']." \n";
# add more fields here if required
## SEND MESSGAE ##
mail( $recipient, $subject, $body, "From: $sender" ) or die ("Mail could not be sent.");
## SHOW RESULT PAGE ##
header( "Location: $location" );
?>
I want to display a thank you message once the person has
successfully filled in the form
I want to check for correct email id eg. if "#" and ".com" has been entered
would it be possible to save the entries to another php or text file ? after the email has been sent ?
Thanks in advance for all replies!

There is a redirect once the mail is sent. Can you place your thank you message on this page? Sometimes I have a thank you.php page for this purpose.
Here is a snippet from a contact form to check for email validation will this help?
if(trim($_POST['email']) === '') {
} else if (!preg_match("/^[[:alnum:]][a-z0-9_.-]*#[a-z0-9.-]+\.[a-z]{2,4}$/i", trim($_POST['email']))) {
$emailError = 'You entered an invalid email address.';
$hasError = true;
} else {
$email = trim($_POST['email']);
}
You could save the entries a database once submitted? Or I think you can create a session to keep hold of the variables for further use. What are you planning to do with the data then after it has been submitted?

Related

php contact form sending mail to server admin [duplicate]

This question already has answers here:
PHP mail function doesn't complete sending of e-mail
(31 answers)
Closed 3 years ago.
I have little issue about my contact form. it doesn't send mail the server admin.
<?php
session_start();
// get the data from the form
$admin_email = 'server#admin.com';
$email = isset($_POST['email']) ? $_POST['email'] : '';
$subject = 'Contact Form';
$name = isset($_POST['name']) ? $_POST['name'] : '';
$message = isset($_POST['message']) ? $_POST['message'] : '';
$captcha = isset($_POST['captcha']) ? $_POST['captcha'] : '';
$img_session = isset($_SESSION['img_session']) ? $_SESSION['img_session'] : '';
$website = $_SERVER['www.mywebsite.com'];
// check if the fields are empty
if(empty($email) or empty($name) or empty($email) or empty($message)){
$output = "All fields are required!";
}else{
if(md5($captcha) == $img_session){
$header = "From: $email"."\r\n"
.'Content-Type: text/plain; charset=utf-8'."\r\n";
$message = "
New entry from $subject!
Name: $name
E-Mail: $email
Message:
$message
This message was sent from http://$website";
if(mail($admin_email, '=?utf-8?B?'.base64_encode($subject).'?=', $message, $header)){
$output = "Your message was sent!<br />Thank you!";
}
}else{
$output = "Wrong captcha code!";
}
}
echo $output;
?>
UPDATED
the wrong part is if $admin_email is not match the contact form email address wrong captcha error pops up? I don't know why. I mean if I don't write contact form email line, same address with admin_email I can't send mail??? What I am trying to do here: send mail to the guest (your mail sent), and also $admin_email: server#admin.com (You have email) $messege.
Form
<form action="" id="contact_form" method="POST">
<p>Name:</p>
<input type="text" name="name" placeholder="Enter name" required=""/>
<p>Email:</p>
<input type="email" name="email" placeholder="Enter email" required=""/>
<p>Message:</p>
<textarea name="message" rows="10" cols="30" required=""></textarea>
<p>Captcha:</p>
<img src="captcha.php" id="captcha"/>
<input type="text" name="captcha" placeholder="Enter code" required=""/>
<input type="submit" value="Submit" />
</form>
If you want to send both email to user and admin, try to call the mail function twice, for example
if(mail($user_email_address, '=?utf-8?B?'.base64_encode($subject).'?=', $message, $header)){
$output = "Your message was sent!<br />Thank you!";
}
if(mail($admin_email_address, '=?utf-8?B?'.base64_encode($subject).'?=', $message, $header)){
$output = "You've got a new message from #user_email_address <br /> ";
}

PHP form is not successfully submitting getting custom error

My PHP form isn't submitting successfully. I keep getting the custom error that I wrote ('Oops there was a problem. Please try again").
any help would be greatly appreciated. I'm totally new to PHP so I'm thinking maybe some of my php variables are linked wrong and arent connecting with my mailer-new.php file?
Thanks in advance,
<section class="form-body">
<form method="post" action="mailer-new.php" class="contact-form" >
<div class="row">
<?php
if ($_GET['success']== 1){
echo " <div class=\"form-messages success\"> Thank you!
your message has been sent. </div>";
}
if ($_GET['success']== -1){
echo " <div class=\"form-messages error\"> Opps there was a
problem. Please try again </div>";
};
?>
<div class="field name-box">
<input type="text" name="name" id="name" placeholder="Who
Are You?" required/>
<label for="name">Name</label>
<span class="ss-icon">check</span>
</div>
<div class="field email-box">
<input type="text" name="email" id="email"
placeholder="name#email.com" required/>
<label for="email">Email</label>
<span class="ss-icon">check</span>
</div>
<div class="field msg-box">
<textarea name="message" id="msg" rows="4"
placeholder="Your message goes here..."/></textarea>
<label for="message">Msg</label>
<span class="ss-icon">check</span>
</div>
<input class="button" type="submit" value="Send"/>
</div>
</form>
</section>
MAILER.PHP
<?php
// Get the form fields, removes html tags and whitespace.
$name = strip_tags(trim($_POST["name"]));
$name = str_replace(array("\r","\n"), array(" ", " " ), $name);
$email = filter_var(trim($_POST["email"]), FILTER_SANITIZE_EMAIL);
$message = trim($_POST["message"]);
// Check the data.
if (empty($name) OR empty($message) OR !filter_var($email, FILTER_VALIDATE_EMAIL)) {
header("Location: http://www.conallen.ie/index.php?
success=-1#form");
exit;
}
// Set the recipient email address. Update this to YOUR desired email address.
$recipient = "allenconallen46#gmail.com";
// Set the email subject.
$subject = "New contact from $name";
// Build the email content.
$email_content = "Name: $name\n";
$email_content .= "Email: $email\n\n";
$email_content .= "Message:\n$message\n";
// Build the email headers.
$email_headers = "From: $name <$email>";
// Send the email.
mail($recipient, $subject, $email_content, $email_headers);
// Redirect to the index.html page with success code
header("Location: http://www.conallen.ie/index.php?success=1#form");
?>
This code works correctly in my local machine, even though email is not sent response messages are coming correctly. The changes I have done is changed the host name and made the two lined header redirect into one line in the failed response. Also you have mentioned in the HTML the file name as action="mailer-new.php" and the file name mentioned in the question as MAILER.PHP. Are they same in the code?
To check whether the mail is sent or not remove the header redirect and update like this. If you are getting a failed response means mail is not configured in your server.
if(mail($recipient, $subject, $email_content, $email_headers)) {
echo "mail sent";
} else {
echo "mail sent failed";
}
Alternatively you can use the SMTP for sending email. You can use a library called PHP Mailer and can use any of the valid email address like a gmail account. Please have look at this question if that's the case
Sending email with PHP from an SMTP server

PHP Form Not Showing Full Information on Submission

I have a very simple form from a template with just three fields - Name - Email - Phone. When submitted the form works. BUT - if in the name field you have two words, e.g, John Smith - then it still submits but then everything after the first word gets truncated - so for the example, the mail received would show only "john" and not show "smith", neither will it show email or phone values. I have given my code samples below.. any help is highly appreciated.
PHP CODE BELOW
<?php
$to = 'x#gmail.com, y#gmail.com' ; // Put in your email address here
$subject = "Appointment Request"; // The default subject. Will appear by default in all messages. Change this if you want.
// User info (DO NOT EDIT!)
$name = stripslashes($_REQUEST['name']); // sender's name
$email = stripslashes($_REQUEST['email']); // sender's email
$phone = stripslashes($_REQUEST['phone']);
// The message you will receive in your mailbox
// Each parts are commented to help you understand what it does exaclty.
// YOU DON'T NEED TO EDIT IT BELOW BUT IF YOU DO, DO IT WITH CAUTION!
$msg = "Name: ".$name."\r\n"; // add sender's name to the message
$msg .= "E-mail: ".$email."\r\n"; // add sender's email to the message
$msg .= "Phone: ".$phone."\r\n"; // add sender's email to the message
$msg .= "Subject: ".$subject."\r\n\n"; // add subject to the message (optional! It will be displayed in the header anyway)
$msg .= "---Message--- \r\n";
$msg .= "\r\n\n";
$mail = #mail($to, $subject, $msg, "From:".$email); // This command sends the e-mail to the e-mail address contained in the $to variable
if($mail) {
echo 'Your message has been sent, we will be in touch shortly!'; //This is the message that will be shown when the message is successfully send
} else {
echo 'Message could not be sent!'; //This is the message that will be shown when an error occured: the message was not send
}
?>
HTML FORM CODE
<form role="form" onSubmit="return send_email();">
<div class="form-group">
<label for="exampleInputName">Name</label>
<input type="text" class="form-control" id="app_name" placeholder="Name" required>
</div>
<div class="form-group">
<label for="exampleInputEmail1">E-mail</label>
<input type="text" class="form-control" id="app_email" placeholder="E-mail" required>
</div>
<div class="form-group">
<label for="exampleInputPassword1">Phone</label>
<input type="text" class="form-control" id="app_phone" placeholder="Phone">
</div>
<button type="submit" class="btn btn-block btn-orange btn-Submit" onclick="ga('send', 'event', 'formsubmit', 'lp form', 'LP form');">Book my Free Consultation</button>
<small id="mail_msg"></small>
</form>
send_email() is actually in a JS file in a separate JS folder.. I have pasted the code below..
JS send_email
function send_email() {
var name=$("#app_name").val();
var email=$("#app_email").val();
var phone=$("#app_phone").val();
if(name=="")
{
$("#app_name").addClass("errors");
}
else
{
$("#app_name").removeClass("errors");
}
if(!validEmail(email))
{
$("#app_email").addClass("errors");
}
else
{
$("#app_email").removeClass("errors");
}
if(phone=="")
{
$("#app_phone").addClass("errors");
}
else
{
$("#app_phone").removeClass("errors");
}
if(name!="" && phone!="" && validEmail(email) )
{
$("#mail_msg").load("email.php?name="+name+"&email="+email+"&phone="+phone);
$("#app_name").val('');
$("#app_email").val('');
$("#app_phone").val('');
}
return false;
}
function validEmail(e) {
var filter = /^\s*[\w\-\+_]+(\.[\w\-\+_]+)*\#[\w\-\+_]+\.[\w\-\+_]+(\.[\w\-\+_]+)*\s*$/;
return String(e).search (filter) != -1;
}

Processing an HTML form with PHP

Well, I have gotten the submit to work... somehow. But the email comes and it only contains my email as the body of the message (not even the email entered into the form)... no name, no phone number, no radio answers, ect.
Ok. I have finally gotten the html form to do SOMETHING. Unfortunately, when you hit "submit" it directs to a page that says this: Internal Server Error
The server encountered an internal error or misconfiguration and was unable to complete your request.
Please contact the server administrator to inform of the time the error occurred and of anything you might have done that may have caused the error.
More information about this error may be available in the server error log.
Here is the PHP code:
<?php
if (!isset($_POST['submit'])) {
//This page should not be accessed directly. Need to submit the form.
echo "error; you need to submit the form!";
}
$name = $_POST['name'];
$telephone = $_POST['phone'];
$visitor_email = $_POST['email'];
//Validate first
if (empty($name) || empty($visitor_email)) {
echo "Name and email are mandatory!";
exit;
}
if (IsInjected($visitor_email)) {
echo "Bad email value!";
exit;
}
$email_from = 'heather#thetrinitydesign.com'; //<== update the email address
$email_subject = "New Form submission";
$email_body = "You have received a new message from the user $name.\n" . "Here is the message:\n $message" . $to = "heather#thetrinitydesign.com"; //<== update the email address
$headers = "From: $email_from \r\n";
$headers .= "Reply-To: $visitor_email \r\n";
//Send the email!
mail($to, $email_subject, $email_body, $headers);
//done. redirect to thank-you page.
header('Location: thank_you.html');
// Function to validate against any email injection attempts
function IsInjected($str)
{
$injections = array(
'(\n+)',
'(\r+)',
'(\t+)',
'(%0A+)',
'(%0D+)',
'(%08+)',
'(%09+)'
);
$inject = join('|', $injections);
$inject = "/$inject/i";
if (preg_match($inject, $str)) {
return true;
} else {
return false;
}
}
?>
And the HTML. I feel like I need to have each of the questions I asked represented in the PHP file. Is this correct? And I have seen so many things preface the $POST thing that I am completely lost.
<form action="form-to-email.php" method="post" enctype="multipart/form-data" name="Info Form" id="Info Form">
<p class="form">Name:
<input name="Name" type="text" class="formbox" id="Name" size="20" />
</p>
<p class="form"> Phone:
<input name="Phone" type="text" class="formbox" id="Phone" size="12" maxlength="12" /></p>
<p class="form">Email:
<span id="sprytextfield2">
<input name="Email" type="text" class="formbox" id="Email" />
<span class="textfieldRequiredMsg">A value is required.</span><span class="textfieldInvalidFormatMsg">Invalid format.</span></span> </p>
<p class="form">
<label>Have you ever had Custom Interior Design work before?<br />
Here is the submit:
<br />
<input name="Submit" type="submit" id="button" value="Submit" />
<br />
</p>
<p class="form">
Just above the validate first comment is a $ that should not be there.
As well as all of the suggestions mentioned, I am going to hazard a guess that the internal error is because the form is posting to 'form-to-email.php', this needs to match the filename of your php file.
change this
<input name="Submit" type="submit" id="button" value="Submit" />
to
<input name="submit" type="submit" id="button" value="Submit" />
^ This should be lowercase here, see below
The code below needs to match the name above.... exactly...
if (!isset($_POST['submit'])) {
^ here!!!!
These two values need to match exactly...
$_POST['THIS'] and <input name="THIS" .../>
As Quinny has pointed out, you make this error with almost all the form inputs...
<input name="Email" .../> should be <input name="email" .../>
<input name="Phone" .../> should be <input name="phone" .../>
<input name="Name" ..../> should be <input name="name" ..../>
It looks to me like you are flying by the seat of your pants, and are just trying to get it working. Spend a little more time learn what is actually happening.
PHP Forms a great tutorial on how to get forms working.
a few things to note:
santize your $_POST data. make sure all data is safe. not just your email data.
look into coding standards, there a bunch, pick one drupals coding standards
give all form elements a name and id, not just an id, when you get into javscript later on, which you may or may not, this will be much easier.
avoid spaces in ids/names form name='Info Form' not a huge deal, could get ugly later on.
you can run the php file from command line, and get some good error details there.
turn on php error reporting Show Errors
these are just a few, not trying to be smug, trying to point you in the right direction.
EDIT:
change this:
$email_from = 'heather#thetrinitydesign.com'; //<== update the email address
$email_subject = "New Form submission";
$email_body = "You have received a new message from the user $name.\n" . "Here is the message:\n $message" . $to = "heather#thetrinitydesign.com"; //<== update the email address
$headers = "From: $email_from \r\n";
$headers .= "Reply-To: $visitor_email \r\n";
//Send the email!
mail($to, $email_subject, $email_body, $headers);
to this:
$message = "Hello My Friend";
$email_from = 'heather#thetrinitydesign.com';
$email_subject = "New Form submission";
$email_body = "You have received a new message from the user $name.\n" . "Here is the message:\n $message";
$to = $_POST['Email']; //<== update the email address
$headers = "From: $email_from \r\n";
$headers .= "Reply-To: $visitor_email \r\n";
//Send the email!
mail($to, $email_subject, $email_body, $headers);
This will send an email from heather#thetrinitydesign.com to "what ever you type in email"
with the message
"You have received a new message from the user "what ever you type in name"
"Here is the message:
Hello My Friend";

Email Notification on new MySQL database entry

I've been creating a blog using tutorials around the web and I have a working comments system but what I would like is if when the user adds a comment that I get an email. I'd really love if you could explain how exactly I could go about implementing a notification. Any help is greatly appreciated.
Current Form:
<form id="commentform" method="post" action="process.php">
<p><input type="hidden" name="entry" id="entry" value="<?php echo $id; ?>" />
<input type="hidden" name="timestamp" id="timestamp" value="<?php echo $commenttimestamp; ?>">
<input type="text" name="name" id="name" title="Name (required)" /><br />
<input type="text" name="email" id="email" title="Mail (will not be published) (required)" /><br />
<input type="text" name="url" id="url" title="Website" value="http://" /><br />
<br />
<textarea title="Your Comment Goes Here" name="comment" id="comment"></textarea></p>
<p><input type="submit" name="submit_comment" id="submit_comment" value="Add Comment" /></p>
</form>
Process.php:
<?php
if (isset($_POST['submit_comment'])) {
if (empty($_POST['name']) || empty($_POST['email']) || empty($_POST['comment'])) {
die("You have forgotten to fill in one of the required fields! Please make sure you submit a name, e-mail address and comment.");
}
$entry = htmlspecialchars(strip_tags($_POST['entry']));
$timestamp = htmlspecialchars(strip_tags($_POST['timestamp']));
$name = htmlspecialchars(strip_tags($_POST['name']));
$email = htmlspecialchars(strip_tags($_POST['email']));
$url = htmlspecialchars(strip_tags($_POST['url']));
$comment = htmlspecialchars(strip_tags($_POST['comment']));
$comment = nl2br($comment);
if (!get_magic_quotes_gpc()) {
$name = addslashes($name);
$url = addslashes($url);
$comment = addslashes($comment);
}
if (!eregi("^([_a-z0-9-]+)(\.[_a-z0-9-]+)*#([a-z0-9-]+)(\.[a-z0-9-]+)*(\.[a-z]{2,4})$", $email)) {
die("The e-mail address you submitted does not appear to be valid. Please go back and correct it.");
}
mysql_connect ('localhost', 'root', 'root') ;
mysql_select_db ('ultankc');
$result = mysql_query("INSERT INTO php_blog_comments (entry, timestamp, name, email, url, comment) VALUES ('$entry','$timestamp','$name','$email','$url','$comment')");
header("Location: post.php?id=" . $entry);
}
else {
die("Error: you cannot access this page directly.");
}
?>
If what you are looking for code in PHP that can send an email, below is one from here for you to look at. Insert the code to send email just before or after you INSERT the comment into your database.
<?php
//define the receiver of the email
$to = 'youraddress#example.com';
//define the subject of the email
$subject = 'Test email';
//define the message to be sent. Each line should be separated with \n
$message = "Hello World!\n\nThis is my first mail.";
//define the headers we want passed. Note that they are separated with \r\n
$headers = "From: webmaster#example.com\r\nReply-To: webmaster#example.com";
//send the email
$mail_sent = #mail( $to, $subject, $message, $headers );
//if the message is sent successfully print "Mail sent". Otherwise print "Mail failed"
echo $mail_sent ? "Mail sent" : "Mail failed";
?>
Requirements:
For the Mail functions to be
available, PHP must have access to the
sendmail binary on your system during
compile time. If you use another mail
program, such as qmail or postfix, be
sure to use the appropriate sendmail
wrappers that come with them. PHP will
first look for sendmail in your PATH,
and then in the following:
/usr/bin:/usr/sbin:/usr/etc:/etc:/usr/ucblib:/usr/lib.
It's highly recommended to have
sendmail available from your PATH.
Also, the user that compiled PHP must
have permission to access the sendmail
binary.

Categories