Some help with the following would be greatly appreciated! I've been searching the web and stackoverflow for hours. There is this problem with my php mail function.
There's a form on my website (the site uses wordpress) with two text fields, name and phone number. There's also a hidden field in the form that displays the current url, so we can see on what page the form was filled in. This information is also stored in a php session.
<?php session_start();
$_SESSION['url'] = $_SERVER['REQUEST_URI'];
?>
<form name="callback" action="callme.php" method="post" onsubmit="return(validate());">
<label>Name:</label><input type="text" name="name" size=15 />
<label>Tel:</label><input class="sky" type="text" name="tel" size=15 />
<div id="afterfive"><p>Call after five<input type="checkbox" name="afterfive" value="Call back after five"></p></div>
<input type="hidden" name="url" value="<?php echo $_SESSION['url']; ?>">
<input type="submit" class="classname" value="Call me back!" title="Call me back!" />
</form>
<script>
function validate()
{
if( document.callme.name.value == "" )
{
alert( "Please fill in your name" );
document.callme.name.focus() ;
return false;
}
if( document.callme.tel.value == "" )
{
alert( "Please fill in your phone number" );
document.callme.tel.focus() ;
return false;
}
}
</script>
The following php code is callme.php:
<?php session_start();
$name = $_POST['name'];
$tel = $_POST['tel'];
$afterfive = $_POST['afterfive'];
$url = $_POST['url'];
$to = "me#myemail.com";
$subject = "Please call back $name";
$message .= "Hi, the following person would like to be called back: \n";
$message .= "Name: $name \n";
$message .= "Phonenumber: $tel \n";
$message .= "$afterfive \n";
$message .= "This message was send from this page: $url \n";
$headers = "From: meagain#myemail.com" . "\r\n";
$headers .= "BCC: meagain#myemail.com" . "\r\n";
if(mail($to, $subject, $message, $headers)){
$_SESSION['name'] = $_POST['name'];
$_SESSION['tel'] = $_POST['tel'];
header("Location: http://www.mywebsite.thankyou");
}
?>
After submitting the form, the visitor is redirected to our thankyou page and given the opportunity the fill in additional information using a second form. The information previously stored in the php session (form fields name, tel and url) are added in hidden form fields.
This all works fine most of the time, but sometimes we receive e-mails with all or some fields empty. Of course this could be users with javascript disabled or google bots that submit blank forms, but the weird thing is that sometimes even the url field is empty (the form is not visible on our homepage). Shouldn't $_SERVER['REQUEST_URI'] always still work?
I was thinking about adding php form validation, but I'm not sure this will solve the problem. Could this have something to do with the hyper cache plug-in for wordpress? Or could it be related to the php session?
"but sometimes we receive e-mails with all or some fields empty"
You should be using a server-side method instead of JS such as
if(empty($_POST['name'])){ die("You need to enter your name.");
(JS can always be disabled by the user, one probable cause for empty emails/fields)
and that will ensure that the fields you wish to be NOT empty, be filled. In conjunction with what Andrewsi mentioned, use if(isset($_POST['submit'])){ at the top of your handler, and name your submit button to name="submit" that way the callme.php if accessed directly, won't process the information without the submit button being clicked.
For example:
Note: There are many other ways to achieve this, but this is a basic yet effective method.
Naming your submit button such as:
<input type="submit" name="submit" value="Submit">
in your case, it would be:
<input type="submit" name="submit" class="classname" value="Call me back!" title="Call me back!" />
PHP handler
<?php
session_start();
if(isset($_POST['submit'])){
if(empty($_POST['name'])){ die("You need to enter your name."); }
if(empty($_POST['tel'])){ die("You need to enter your telephone number."); }
if(empty($_POST['afterfive'])){ die("You need to fill this field."); }
if(empty($_POST['url'])){ die("You need to fill this field."); }
$name = $_POST['name'];
$tel = $_POST['tel'];
$afterfive = $_POST['afterfive'];
$url = $_POST['url'];
$to = "me#myemail.com";
$subject = "Please call back $name";
$message .= "Hi, the following person would like to be called back: \n";
$message .= "Name: $name \n";
$message .= "Phonenumber: $tel \n";
$message .= "$afterfive \n";
$message .= "This message was send from this page: $url \n";
$headers = "From: meagain#myemail.com" . "\r\n";
$headers .= "BCC: meagain#myemail.com" . "\r\n";
if(mail($to, $subject, $message, $headers)){
$_SESSION['name'] = $_POST['name'];
$_SESSION['tel'] = $_POST['tel'];
header("Location: http://www.mywebsite.thankyou");
}
}
// You could use this at end also to show a message
// if callme.php is accessed directly.
// else {echo "You cannot do that from here.";exit;}
?>
Your javascript refers to document.callme, but there is nothing in your code with that name.
Related
The PHP code sends me an email from the server, but the user input is empty or "blank". I only receive: "From: \ Email: \ Subject: \ Message: " and that's it.
How do I fix my PHP and/or HTML code to receive user input from the form? Here is my existing HTML and PHP code that doesn't send me any "user input" from the form.
PHP
HTML
Thanks to anyone who can help!!
Consider this is your form
<form action="yourpage.php" method="post">
<input type="text" name="name" placeholder="enter name" required>
<input type="submit" name="submit" placeholder="enter name">
Make sure that <form action="" is linking to correct page and method="post" should be there.
If form is there on current page i.e. in my case its yourpage.php then leave form action blank. Also i recommend adding required in end of input field e.g.
<input type="text" name="name" placeholder="enter your name" required>
as it forces user to write some value there so you dont get a empty value
Next will be your php file, just add a code in first line
if(isset($_POST['submit'])) {
above code verifies that user clicks on submit button so overall code will look like
<?php
if(isset($_POST['submit'])) {
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phoneT'];
$call = $_POST['call'];
$website = $_POST['website'];
$priority = $_POST['priority'];
$type = $_POST[itypel];
$message = $_POSTUmessagefl;
$formcontent = " From:$name \n Phone: $phone \n CallBack: $call \n Website: $website \n Priority: $priority \n Type: $type \n Message: $message";
$recipient = "YOUREMAIL#HERE.COM";
$subject - "Contact Form";
$mailheader = "From: $email \r\n";
mail($recipient, $subject, $formcontent, $mailheader) or die("Error!");
echo "Thank You!" . " -" . "<a href=iform.htmll
style='text-decoration:none;color:#ff0099;'> Return
Home</a>";
}
?>
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I used this post to make a simple ‘contact us’ form. The form collects a few pieces of information (email, name and a message) from your visitor and emails it to you.
Instead of redirecting to a thank you page, I'd prefer it to just print the thank you (or error) text in the same HTML form page.
How can this be done? Where do I need to change to be able to keep the user in the same page and show the confirmation message ("Thank you")?
Edit: Found a much simpler way to do this - with ajax.
Here is my suggestion.
1- Change your file name contact-form.html to contact-form.php
2- Added include line and edit your form action in contact-form.php:
<h1>Contact us</h1>
<?php include './contact-form-handler.php'; ?>
<form method="POST" name="contactform" action="#">
3- Edit your contact-form-handler.php, disable header and added your thank you with personal message, you can also added some layout and decoration that is left to your fantasy.
//header('Location: contact-form-thank-you.html');
echo "Thank you " . $name . "<br />";
echo "We will contact you soon";
4- Last thing I will added condition to check if the form is submitted or not
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
if (empty... etc
}
5- (Optional) To re-fetch the posted values if failed I have added following to the form inputs (3 of them, each field got one with the respective field/variable name):
value="<?php if (isset($_POST['name'])) echo $name; ?>"
But in general When all this done, I will personally will go through the form and clean it up a little bit. Like if I am check the content in JavaScript it is not necessary to check if the fields are empty, so checking submission form is enough. I have not talk about form security yet against any kind of misuse, this just to make some thoughts when you come so far.
Complete code
Here is your final results, with extra things I done:
contact-form.php
<form method="POST" name="contactform" action="#">
<p>
<label for='name'>Your Name:</label> <br>
<input type="text" name="name" value="<?php if (isset($_POST['name'])) echo $name; ?>">
</p>
<p>
<label for='email'>Email Address:</label> <br>
<input type="text" name="email" value="<?php if (isset($_POST['email'])) echo $email_address; ?>"> <br>
</p>
<p>
<label for='message'>Message:</label> <br>
<textarea name="message" value="<?php if (isset($_POST['message'])) echo $message; ?>"></textarea>
</p>
<input type="submit" value="Submit"><br>
</form>
contact-form-handler.php
<?php
$errors = '';
$myemail = 'yourname#website.com';//<-----Put Your email address here.
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
if (empty($_POST['name']) ||
empty($_POST['email']) ||
empty($_POST['message'])
)
{
$errors .= "\n Error: all fields are required";
}
$name = $_POST['name'];
$email_address = $_POST['email'];
$message = $_POST['message'];
if (!preg_match(
"/^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/i",
$email_address)
)
{
$errors .= "\n Error: Invalid email address";
}
if (empty($errors))
{
$to = $myemail;
$email_subject = "Contact form submission: $name";
$email_body = "You have received a new message. " .
" Here are the details:\n Name: $name \n Email: $email_address \n Message \n $message";
$headers = "From: $myemail\n";
$headers .= "Reply-To: $email_address";
mail($to, $email_subject, $email_body, $headers);
//redirect to the 'thank you' page
//header('Location: contact-form-thank-you.html');
echo "Thank you " . $name . "<br />";
echo "We will contact you soon";
$name = "";
$email_address = "";
$message = "";
}
}
?>
Like the title says, sending a form to my email. I get no errors, but the email never comes. Here's my HTML form (I don't think you'll need anything else, but there is also some formatting and Java verification in the file).
<form method="POST" name="contactform" action="contact-form-handler.php">
<p>
<label for='name'>Your Name:</label>
<br>
<input type="text" name="name">
</p>
<p>
<label for='email'>Email Address:</label>
<br>
<input type="text" name="email">
<br>
</p>
<p>
<label for='message'>Message:</label>
<br>
<textarea name="message"></textarea>
</p>
<input type="submit" value="Submit">
<br>
</form>
And here's my PHP. Obviously I took my email out and put in EMAIL instead, but other than that this is my complete PHP file. The thank you PHP file pulls up the submitted page just fine, and I get no errors. Just no email either.
<?php
$errors = '';
$myemail = 'EMAIL#gmail.com';
if(empty($_POST['name']) ||
empty($_POST['email']) ||
empty($_POST['message']))
{
$errors .= "\n Error: all fields are required";
}
$name = $_POST['name'];
$email_address = $_POST['email'];
$message = $_POST['message'];
if (!preg_match(
"/ ^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/i",
$email_address))
{
$errors .= "\n Error: Invalid email address";
}
if( empty($errors))
{
$to = '$myemail';
$email_subject = "Contact form submission: $name";
$email_body = "You have received a new message. ".
" Here are the details:\n Name: $name \n ".
"Email: $email_address\n Message \n $message";
$headers = "From: $myemail\n";
$headers .= "Reply-To: $email_address";
mail($to,$email_subject,$email_body,$headers);
//redirect to the 'thank you' page
header('Location: contact-form-thank-you.html');
}
?>
Thanks ahead of time for any help you can provide! I can give the rest of my HTML file or my other PHP file if you need it, this is where all the real functionality lies though.
*PHP to send form data to an email i have used this code as well as its work for me .you can try *
<?PHP
$email = $_POST["emailaddress"];
$to = "you#youremail.com";
$subject = "New Email Address for Mailing List";
$headers = "From: $email\n";
$message = "A visitor to your site has sent the following email address to be added to your mailing list.\n
Email Address: $email";
$user = "$email";
$usersubject = "Thank You";
$userheaders = "From: you#youremailaddress.com\n";
$usermessage = "Thank you for subscribing to our mailing list.";
mail($to,$subject,$message,$headers);
mail($user,$usersubject,$usermessage,$userheaders);
?>
after that you can addded your futher code
Try add in top file:
error_reporting(E_ALL);
and edit your code, see:
if(mail($to,$email_subject,$email_body,$headers)){
//redirect to the 'thank you' page
header('Location: contact-form-thank-you.html');
} else {
echo 'Error!';
}
Read this:
http://www.php.net/manual/en/function.error-reporting.php
http://www.php.net/errorfunc
http://php.net/manual/pt_BR/function.set-error-handler.php
http://www.php.net/register_shutdown_function
you have the variable $myemail as a string value after $to = Remove the parentheses and your code will work
The problem is with your From field in your $headers variable.
you can't just put any email address in there. For example: you are supposed to put an existing email address of your server that you create. Or if you want to use a gmail account in from field, you need to configure your gmail username and password with your server first before using that email.
The simplest solution is to create a new email address on your hosting server and then put that email address in your from field in $headers variable.
I've already mentioned it in details here.
I made captcha by this [tutorial][1],
[1]: http://codechirps.com/how-to-add-a-completely-custom-captcha-to-any-web-form/ but it seems to me it doesn't complete.
I made code but i can send email even if i put wrong answer. I feel that i have to write extra code in php file but i don't know where. Any help greatly appriciated
<div class="modal-body">
<form class="contact" name="contact">
<label class="label" for="name">Имя</label><br>
<input type="text" name="name" class="input-xlarge"><br>
<label class="label" for="email">E-mail</label><br>
<input type="email" name="email" class="input-xlarge"><br>
<label class="label" for="message">Сообщение</label><br>
<textarea name="message" class="input-xlarge"></textarea>
</form>
</div>
<div class="modal-footer">
<p>2 + 3 =</p>
<input type="text" name="captcha" />
<input class="btn btn-warning" type="submit" value="Отправить" id="submit">
Закрыть
<?php
$myemail = '';
if (isset($_POST['name'])) {
$name = strip_tags($_POST['name']);
$email = strip_tags($_POST['email']);
$message = strip_tags($_POST['message']);
$captcha = check_input($_POST['captcha']);
echo "<span class=\"alert alert-success\" >Сообщение отправлено</span><br><br>";
if (!preg_match("/5/", $captcha))
{
show_error("Check your math, Dude");
}
$to = $myemail;
$email_subject = "Contact form submission: $name";
$email_body = "You have received a new message. ".
" Here are the details:\n Name: $name \n ".
"Email: $email\n Message \n $message";
$headers = "From: $myemail\n";
$headers .= "Reply-To: $email";
mail($to,$email_subject,$email_body,$headers);
}?>
Okay, so you need to check the values of your inputs to see if they are valid. If not, you display an error and the mail doesn't get sent. If all the checks pass, the maildoes get sent. So you need to check the $_POST['email'] and the $_POST['captcha'] field (and if you want to, check if the rest isn't empty or whatever).
In php, you can do this like this:
$myemail = "";
if(isset($_POST['name'])){ // check if a form is submitted
if(empty(trim($_POST['name'])) || empty(trim($_POST['message'])) || empty(trim($_POST['email'])) || empty(trim($_POST['captcha'])) ){ // check if values are not empty
echo "Please fill in all the required fields.";
}else if(!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)){ // check email
echo "Please give a real e-mail address.";
}else if(!preg_match("/5/", $_POST['captcha'])){ // the code provided by your script
echo "Get your math right, dude!";
}else{ // all fields seem to be ok
// sanitize input using htmlspecialchars(), see http://stackoverflow.com/a/5788361/1319187
$name = htmlspecialchars($_POST['email']);
$email = $_POST['email']; // email doesn't need to be sanitized since it's been filtered
$message = htmlspecialchars($_POST['message']);
//Send the mail
$to = $myemail;
$email_subject = "Contact form submission: $name";
$email_body = "You have received a new message. ".
" Here are the details:\n Name: $name \n ".
"Email: $email\n Message \n $message";
$headers = "From: $myemail\n";
$headers .= "Reply-To: $email";
if(mail($to,$email_subject,$email_body,$headers)){
echo "Succes! Your mail has been sent!";
}else{
echo "Something went wrong with the sending of a mail.";
}
}
}
Should be rather straightforward, you can google some functions if you don't know what they do.
I also have no idea where check_input() comes from. It's not a native PHP function, and the link you provided doesn't show what it does. Also, the regex to check whether the value of the captcha is 5 is a bit stupid, you could just check $_POST['captcha'] == '5'. Also keep in mind you have to randomize these values a bit.
I have a problem with my contact form. When I fill it on my website, I get an e-mail, but fields: Name, eMail and Message remain blank in my received e-mail.
My contact complex consists of: contacts.html (html page on my website); contactengine.php (an actual form); thanks.html (it opens when a question is successfully posted); unsuccessful.html (opens when unsuccessful).
Can anyone tell me what's wrong with this code?
CONTACTS.HTML
<form id="form" form action="contactengine.php" method="post" >
<fieldset>
<label><input type="text" name="cf_name" value="Name" id="cf_name" onBlur="if(this.value=='') this.value='Name'" onFocus="if(this.value =='Name' ) this.value=''"></label>
<label><input type="text" name="cf_email" value="e-Mail" id="cf_email" onBlur="if(this.value=='') this.value='e-Mail'" onFocus="if(this.value =='e-Mail' ) this.value=''"></label
<label><textarea name="cf_message" id="cf_message" onBlur="if(this.value==''){this.value='Message'}" onFocus="if(this.value=='Message'){this.value=''}">Message</textarea></label>
<div class="btns">
Cancel
Submit</div>
</fieldset>
</form>
CONTACTENGINE.PHP
<?php
$EmailFrom = "form#mysite.rs";
$EmailTo = "office#mysite.rs";
$Subject = "Message from website";
$cf_name = Trim(stripslashes($_POST['Name']));
$cf_email = Trim(stripslashes($_POST['Email']));
$cf_message = Trim(stripslashes($_POST['Message']));
// validation
$validationOK=true;
if (!$validationOK) {
print "<meta http-equiv=\"refresh\" content=\"0;URL=unsuccessful.html\">";
exit;
}
// prepare email body text
$Body = "";
$Body .= "Name: ";
$Body .= $cf_name;
$Body .= "\n";
$Body .= "e-Mail: ";
$Body .= $cf_email;
$Body .= "\n";
$Body .= "Message: ";
$Body .= $cf_message;
$Body .= "\n";
// send email
$success = mail($EmailTo, $Subject, $Body, "From: <$EmailFrom>");
// redirect to success page
if ($success){
print "<meta http-equiv=\"refresh\" content=\"0;URL=thanks.html\">";
}
else{
print "<meta http-equiv=\"refresh\" content=\"0;URL=unsuccessful.html\">";
}
?>
The lines:
$cf_name = Trim(stripslashes($_POST['Name']));
$cf_email = Trim(stripslashes($_POST['Email']));
$cf_message = Trim(stripslashes($_POST['Message']));
should be changed to
$cf_name = Trim(stripslashes($_POST['cf_name']));
$cf_email = Trim(stripslashes($_POST['cf_email']));
$cf_message = Trim(stripslashes($_POST['cf_message']));
The variable name doesn't matter, but the text inside $_POST[''] should be the same as the name value for the form element!
You prefixed the names in your HTML with cf_, but didn't do the same in your PHP!
EDIT: Oops, I missed something!
You are linking to contactengine.php with an <a> link!
Your browser treats this as a regular GET request, and doesn't send the data with it!
Even though you put JavaScript code to submit the form, the browser's default action (to go to the link) overpowers your code.
To fix this, either
Change the last <a> tag in contacts.html to <input type="submit" value="Submit" />, turning the link into a submit button, or
Add ; return false; to the end of your onclick handler for the submitting link. This stops the browser from doing its default behavior, and submits the form.