Some $_POST arrays are sometimes empty when using PHP mail - php

I'm having some problems in using php mail function to send a html form's data. The mail function is working fine and I have no problem receiving the email when the form is submitted, but sometimes I got empty arrays in my email.
The code looks like:
<?php
error_reporting(E_ALL & ~E_NOTICE);
$email = $_POST['email'];
//check if value is set:
if (isset($_POST['submit'])){
$everyoneToppingList = substr(implode(', ', $_POST['everyone_platter_topping']), 0);
$everyoneCondimentList = substr(implode(', ', $_POST['everyone_platter_condiment']), 0);
}; //end isset($_POST['submit']
$len = strlen($email);
if ($len > 0)
{
$email_body = "Full Name: $title $fullname\n".
"Topping? - $everyoneToppingList\n".
"Condiment? - $everyoneCondimentList\n\n";
$email_to = "example#gmail.com";
$email_from = $_POST['email']; // required
$URL= "order.php";
header ("Location: $URL");
// create email headers
$headers = "From: $email_from \r\n";
$headers .= "Reply-To: $email_from \r\n";
$headers .= "Cc: $email_from \r\n";
$headers .= "X-Mailer: PHP/". phpversion();
mail($email_to, $email_subject, $email_body, $headers);
} ?>
And the html part looks like:
<table style="vertical-align:top;" class="form platter bread" cellspacing="2">
<tr>
<span class="bold">
Choose Your Topping:
</span>
<span id="errorsDiv_everyone_platter_topping[]">
</span>
<td height="7" width="87" align="left" valign="middle">
<input type="checkbox" name="everyone_platter_topping[]" value="Lettuce" id="everyone_lettuce" />
<label for="everyone_lettuce">\
Lettuce
</label>
</td>
<td height="7" width="87" align="left" valign="middle">
<input type="checkbox" name="everyone_platter_topping[]" value="Tomatoes" id="everyone_tomatoes" />
<label for="everyone_tomatoes">
Tomatoes
</label>
</td>
</tr>
</table>
When I receive the email, sometimes it only shows "Topping? - , , , ," .
Really need help on this and any suggestions will be appreciated!!
Thank you!

I am sorry to write it over here, but comment section is not enough to mention the doubts regarding your question.
the elements in the form and the elements used in PHP code does not give clear picture of the question.
Also $URL= "order.php";
header ("Location: $URL"); does not make any sense, it will redirect and mail wont be sent anyways
If I make this subtle changes of
removing header code from the PHP code
adding the email input box and submit submit button in the html form
adding form outside the table with method POST
I simply got this code working by making above changes without any trouble.
I suggest you edit a question and ask again or do the suggested changes (of course with some tweaking from your side) and you will code be in working state.

First initialize your variables before using em.
$everyoneToppingList = null;
$everyoneCondimentList = null;
if (isset($_POST['submit'])){
$everyoneToppingList = substr(implode(', ', $_POST['everyone_platter_topping']), 0);
$everyoneCondimentList = substr(implode(', ', $_POST['everyone_platter_condiment']), 0);
};
$len = strlen($email);
if ($len > 0)
{
if (!is_null($everyoneToppingList) && !is_null($everyoneCondimentList))
{
// Send your mail.
}
}

Related

Php send mail works but something is going on [duplicate]

This question already has answers here:
Check form input length via PHP with maxlength tag
(1 answer)
Prevent php web contact form spam
(11 answers)
Closed 1 year ago.
I have a php website that is working well. It's allows customer to make online reservation and email is sent to us. We have message field, number of passenger and others. The message field is set to 30 characters limit and number of passenger limit is 2 characters. Works well. However, some hackers are being overwitten the message field to like 1000 characters and number field to 20 characters. These people are like telemaketers. What and how can I prevent this. Do I need to install some security software? Which one?Please suggest. Thanks in advance.
Here's the code
/// Contact page
# of Passenger:
<textarea maxlength="150" placeholder="Message/Notes" rows="5" COLS="60" name="notes" title="Note/Message" style="height:71px; width:133px; margin-top:-47px;margin-left:175px;"></textarea>
<input type="submit" name="submit" value="Send"> <input type="button" value="Cancel" onClick="window.location='index.php';" name="Cancel" >
/// iProcess page
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$notes = $_POST['notes'];
$notes = htmlentities($notes, ENT_QUOTES, 'UTF-8');
$passenger = $_POST['passenger'];
//// email send here
$to = "info#mytest.com"; // Tracking customer for sometime. would remove my email later
$subject = "Reservation";
$message ="
<html>
<head>
<title>Reservation Email</title>
</head>
<body>
<p>Customer Reservation information </p>
<table>
<tr>
<th>Order Number :</th>
<td>$ordernumber</td>
</tr>
<tr>
<th>Number of Passenger :</th>
<td>$passenger</td>
</tr>
<tr>
<th>Messages/Notes :</th>
<td>$notes</td>
</tr>
</table>
</body>
</html>
";
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
////// more headers
//$headers .= 'From: <info#mytest.com' . "\r\n";
//$headers .= 'Cc: <>' . "\r\n";
$success = mail($to,$subject,$message,$headers);
if (!$success) {
$errorMessage = error_get_last()['message'];
}
else
{ echo "Email send successfully"; }
}
else
{
echo "Unable to connect or send your reservation!";
}
}

How to redirect to home page after submitting the Contact Form?

i have created contact form but i am getting two problems
Reply-To mail is not going.
After Submitting the form page has to redirect to Home page.
For reference please find the attached image and code
Below is the PHP code
<?php
if(isset($_POST['submit']))
{
$name = $_POST['name']; // Get Name value from HTML Form
$email_id = $_POST['email']; // Get Email Value
$mobile_no = $_POST['Mobile']; // Get Mobile No
$msg = $_POST['message']; // Get Message Value
$to = "somasekhar.n#vitalticks.com"; // You can change here your Email
$subject = "'$name' has been sent a mail"; // This is your subject
// HTML Message Starts here
$message ="
<html>
<body>
<table style='width:600px;'>
<tbody>
<tr>
<td style='width:150px'><strong>Name: </strong></td>
<td style='width:400px'>$name</td>
</tr>
<tr>
<td style='width:150px'><strong>Email ID: </strong></td>
<td style='width:400px'>$email_id</td>
</tr>
<tr>
<td style='width:150px'><strong>Mobile No: </strong></td>
<td style='width:400px'>$mobile_no</td>
</tr>
<tr>
<td style='width:150px'><strong>Message: </strong></td>
<td style='width:400px'>$msg</td>
</tr>
</tbody>
</table>
</body>
</html>
";
// HTML Message Ends here
// Always set content-type when sending HTML email
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
// More headers
$headers .= "From: New Contact Form <".$_POST["email"].">\r\n"; // Give an email id on which you want get a reply. User will get a mail from this email id
$headers .= 'Cc: somumstr210#gmail.com' . "\r\n"; // If you want add cc
// $headers .= 'Bcc: somasekhar.n#vitalticks.com' . "\r\n"; // If you want add Bcc
$headers .= "Reply-To: ".$_POST["email"]."\r\n";
if(mail($to,$subject,$message,$headers)){
// Message if mail has been sent
echo "<script>
alert('Mail has been sent Successfully.');
</script>";
}
else{
// Message if mail has been not sent
echo "<script>
alert('EMAIL FAILED');
</script>";
}
}
?>
The mail function is deprecated and may not work right! I recommand phpmailer https://github.com/PHPMailer/PHPMailer
How do I make a redirect in PHP?
header("Location: path/to/file");
please check post variables
$variable = $_POST['variable-name'] ?? "default content if $_POST['variable-name'] is undefined";
EDIT: mail() is not deprecated but please use the PHPmailer because it's better

Upon submitting form, scroll to vertical position on page

I have created a simple html/php form where visitors on my site can write their name, email and message and then send the message to my email. Problem is that when they submit the email, my site then performs a full refresh (it looks like) and therefore just reloads to the top of my site. I would like for the user to remain at the same scroll position after submit, so that they can instantly see whether the submit was succesful or not. So either a solution that prevents the refresh or some other solution that automatically scrolls down vertical to the form.
Can you tell me if this is possible using php? Or do I have to use some jquery/ajax solution?
Below is the code I am using. I am a complete novice, so please be gentle.
<form action="" method="post" id="form">
<div class="contact-info-group">
<label for="name"><span>Your name</span>
<input type="text" id="name" name="name" autocomplete="off" value="<?php echo $name; ?>"></label>
<label for="email"><span>Your email</span>
<input type="email" id="email" name="email" autocomplete="off"></label>
</div>
<label for="message"><span>Your message</span>
<textarea id="message" name="message"></textarea></label>
<input id="button1" type="submit" class="button next" name="contact_submit" value="Send message">
<?php
// Check for header injections
function has_header_injection($str) {
return preg_match("/[\r\n]/", $str);
}
if (isset ($_POST['contact_submit'])) {
$name = trim($_POST['name']);
$email = trim($_POST['email']);
$msg = $_POST['message'];
// Check to see if $name or $email have header injections
if (has_header_injection($name) || has_header_injection($email)) {
die();
}
if (!$name || !$email || !$msg) {
echo '<div class="contact-warning"><h2>! Error - Please note that all of the above fields are required !</h2></div>';
exit;
}
// Add the recipient email to a variable
$to = "email#email.com";
// Create a subject
$subject = "Message via website.com - $name";
// Construct the message
$message = "Name: $name\r\n";
$message .= "Email: $email\r\n";
$message .= "Message: \r\n\r\n$msg";
// Clean up the message
$message = wordwrap($message, 72);
// Set the mail headers into a variable
$headers = "MIME-Version 1.0\r\n";
$headers .= "Content-type: text/plain; charset=iso-8859-1\r\n";
$headers .= "From: $name <$email> \r\n";
$headers .= "X-Priority: 1\r\n";
$headers .= "X-MSMail-Priority: High\r\n\r\n";
// Send the email
mail($to, $subject, $message, $headers);
echo '<div class="contact-warning"><h2>Thank you for your message. We will get back to you shortly.</h2></div>';
}
?>
</form>

HTML / PHP contact form doesn't send data to my gmail

i've been trying to fix this one with solutions i've found here and in other foruns but nothing seems to work. I'm really noob with PHP. I don't know if this info is relevant but i'm hosting my project at byethost.com which they say it supports PHP.
I have made a contact form in my HTML contact page, made a PHP file to process the data and send it to my gmail adress. It says message successfully sent, but the data never arrives at my inbox on gmail. I've tried changing the PHP code (with copy paste solutions) in alternative ways but with no luck. I've also tried to sent it to my hotmail account but it doesn't work either. Can anyone help me?
Here is the HTML contact form:
<div id="form_wrap">
<form method="post" action="form_process.php" id="contact_form" class="contact">
<label>
<span>NOME*</span>
<input name="nome" type="text" tabindex="1" required>
</label>
<label>
<span>E-MAIL*</span>
<input name="email" type="email" tabindex="2" required>
</label>
<label>
<span>TELEFONE*</span>
<input name="phone" type="tel" tabindex="3" required>
</label>
<label>
<span>WEBSITE</span>
<input name="website" placeholder="http://" type="url" tabindex="4">
</label>
<label>
<span>MOTIVO DE CONTACTO*</span>
<select class="escolha" name="motivo" size="1" tabindex="5" required>
<option>Contratá-lo</option>
<option>Fazer uma pergunta</option>
<option>Dizer olá ou agradecer</option>
</select>
</label>
<div>
<label>
<span>MENSAGEM*</span>
<textarea name="message" tabindex="6" required></textarea>
</label>
</div>
<div>
<input name="submit" type="submit" value="Enviar" id="submit">
</div>
</form>
<a class="subtop" href="#subtop">– Voltar ao topo</a>
</div>
Here is my form_process.php:
<?php
if(isset($_POST['submit'])) {
$nome = $_POST['nome'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$website = $_POST['website'];
$motivo = $_POST['motivo'];
$message = $_POST['message'];
$to = "mygmailadress#gmail.com";
$subject = "Site contact form";
$header = "From: ".$fromText."\r\n";
$header .= "Cc: ".$ccText."\n";
$header .= "Reply-To : ".$fromText."\r\n";
$header .= "Return-Path : ".$fromText."\r\n";
$header .= "X-Mailer: PHP\r\n";
$header .= "MIME-Version: 1.0\r\n";
$header .= "Content-Type: text/plain; charset=iso-8859-1\r\n";
mail($to, $subject, $header, $message, "From: " . $nome);
}
if(#mail($emailRecipient, $subject, $message, $headers))
{
echo "Mail Sent Successfully";
}else{
echo "Mail Not Sent";
}
?>
Why twice mail function?
mail has 4 parameters, you give 5 params (from is a paert of fourth, it should be in $header)
variable $emailRecipient used in your mail function doesn't exists.
in 'from' header should be an e-mail address (and name), not only a non-mail string
There are many possible reasons that the email never arrives.
It could be caught in spam, blocked by your host or your mail function could be incorrectly setup in your php.ini file.
However, from your code it looks like you are using the mail() function incorrectly.
You are trying to send the email twice by calling the function twice. Just call it once like:
if(mail(...)) {
echo 'good times';
} else {
echo 'boo, no email was sent';
}
Secondly you are using the function incorrectly. According to the documentation here the mail function takes five arguments like so:
bool mail ( string $to , string $subject , string $message [, string $additional_headers [, string $additional_parameters ]] )
$additional_headers and $additional_parameters are optional as denoted by the [square brackets]. $to, $subject and $message are required in that order.
Thirdly I heavily suggest NOT using the built in mail() function.
I suggest using SwiftMailer. It's a fully comprehensive PHP library which will look after you.
U are trying to send mail twice you are using wrong variable names.
This code works for me.
<?php
if(isset($_POST['submit'])) {
$nome = $_POST['nome'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$website = $_POST['website'];
$motivo = $_POST['motivo'];
$message = $_POST['message'];
$to = "asdf#gmail.com";
$subject = "Site contact form";
$header = "From: ".$email."\r\n";
$header .= "Cc: ".$email."\n";
$header .= "Reply-To : ".$email."\r\n";
$header .= "Return-Path : ".$email."\r\n";
$header .= "X-Mailer: PHP\r\n";
$header .= "MIME-Version: 1.0\r\n";
$header .= "Content-Type: text/plain; charset=iso-8859-1\r\n";
if(mail($to, $subject, $message, $header))
{
echo "Mail Sent Successfully";
}else{
echo "Mail Not Sent";
}
}
?>
If you are usinf free hosting, they probably restrict your ability to send email.
Something like that is happening:
https://www.freehosting.com/client/knowledgebase.php?action=displayarticle&id=25
PHP mailing functionality is limited on free account to prevent abuse. To make it working, your mailing script should be configured to use SMTP server 'cpanel.freehosting.com' and to authenticate against it using credentials of email account set up in cpanel.
Paid accounts are provided with unrestricted access to PHP mailing functionality.
You can find more info on setting up email authentication in PHP scripts at this link:
http://email.about.com/od/emailprogrammingtips/qt/PHP_Email_SMTP_Authentication.htm
Optionally, PHP mail() can be enabled by purchasing corresponding addon HERE.

empty $_POST in PHP mail()

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.

Categories