send html form with php can't solve - php

I have big problem with sending easy html form with php.
My problem is when all fields are empty it still send message.
I don't why this code still send empty form??
<form id="form1" name="form1" method="post" action="forma.php">
<p>
<label for="ime">Ime:</label>
<input type="text" name="ime" id="ime" />
</p>
<p>
<label for="prezime">Prezime:</label>
<input type="text" name="prezime" id="prezime" />
</p>
<p>
<label for="email">e-mail:</label>
<input type="text" name="email" id="email" />
</p>
<p>
<label for="poruka">Poruka:</label>
<textarea name="poruka" cols="40" rows="10" id="poruka"></textarea>
</p>
<p>
<input type="submit" name="submit" value="submit" />
</p>
</form>
My php code:
<?php
if (isset($_POST['submit']))
{
$ime= $_POST['ime'];
$prezime= $_POST['prezime'];
$email= $_POST['email'];
$poruka= $_POST['poruka'];
$email_from = 'neki#email.com';
$email_subject = "forma sa sajta";
$email_body = "Ime: $ime. \n". "Prezime: $prezime \n". "email: $email \n". "poruka: $poruka" ;
$to = "myemail#gmail.com";
mail ($to, $email_subject, $email_body);
echo "Message is sent";
}
else {
echo "Message is not sent";
}
?>
So again, when i fill fields message is sent. It is ok, i received email.
But when i just click submit (without filling fields) it still send message to my email.
What is wrong with this code? I try everything i know, but without success.
Thank you.

The problem is that you are only checking to see if "submit" is set.
Your if statement should read something like:
if(isset($_POST['submit']) && all_other_fields_are_valid($_POST)){...}
function all_other_fields_are_valid($fields)
{
//logic to decide what fields and values you require goes here
}

You need to check all required field. only check submit it will attempt mailing:
if (isset($_POST['submit']
, $_POST['ime']
, $_POST['prezime']
, $_POST['email']
, $_POST['poruka']))
Additionally you can validate from the client side using new HTML5 required attribute:
<input type="text" name="ime" id="ime" required />
This way you don't waste server resources for bad formed requests.

Actually since they are sent as empty variables, they will still evaluate to true in isset(), even if there is no text in the input fields when they are submitted.
if($_POST['ime'] && $_POST['prezime'] && $_POST['email'] && $_POST['poruka']) {
// do stuff here
}
As long as all of these have values and none of the values are 'false' or '0', this will evaluate to true only if somebody puts text in all of the input fields.

This will check if all required POST vars are set, if they're empty and give an error if so:
<?php
if (isset($_POST['submit'], $_POST['ime'], $_POST['prezime'], $_POST['email'], $_POST['poruka']))
{
$error = "";
if($_POST['ime'] == ""){
$error .= "ima was empty!<br />";
}
if($_POST['prezime'] == ""){
$error .= "prezime was empty!<br />";
}
if($_POST['email'] == ""){
$error .= "email was empty!<br />";
}
if($_POST['poruka'] == ""){
$error .= "poruka was empty!<br />";
}
if($error == ""){
$ime= $_POST['ime'];
$prezime= $_POST['prezime'];
$email= $_POST['email'];
$poruka= $_POST['poruka'];
$email_from = 'neki#email.com';
$email_subject = "forma sa sajta";
$email_body = "Ime: $ime. \n". "Prezime: $prezime \n". "email: $email \n". "poruka: $poruka" ;
$to = "myemail#gmail.com";
mail ($to, $email_subject, $email_body);
echo "Message is sent";
} else {
echo $error;
}
} else {
echo "Message is not sent";
}
?>

Related

How to "see" php variable in multiple <?php ?>

Ok i will show you code, you should understand from it what i want, problem is it doesnt recognize variable from one php tags inside other php tags on same page which is contact.php...
<form action="contact.php" method="POST">
<p>Name: <input type="text" name="name"><?php $nameErr=' '; echo $nameErr; ?></p>
<p>Email: <input type="email" name="email"><?php $emailErr=' '; echo $emailErr; ?></p>
<p>Message:</p> <textarea name="message" rows="10" cols="50"></textarea><br />
<p><?php $messageErr= ' '; echo $messageErr; ?></p>
<button type="submit" value="Submit" name="Submit1">Submit</button>
</form>
<?php
if (isset($_POST['Submit1'])) {
$name = $_POST['name'];
$email= $_POST['email'];
$message= $_POST['message'];
$formcontent= "From: $name \n Message: $message";
$recipient= "konstantin91#gmail.com";
$subject= "Contact Form";
$mailheader= "From: $email \r\n";
if(strlen($name)==0) {
$nameErr = "Name is required <br>";
die();
}
elseif(strlen($email)==0) {
$emailErr = "Email is required";
die();
}
elseif(strlen($message)==0) {
$messageErr "Message is required <br>";
die();
}
else {
echo "$name, thank you for submiting message";
}
}
?>
I made all $varErr variables empty strings by default so when you first enter contact.php you see nothing, but when you submit form IF checks if field is empty, if it is empty i want inline with form field to echo $varErr for that field ($nameErr or $emailErr, $messageErr will go under textarea field cause i want it like that)
Hope you understand what i want, i have finished everything just that form and i am done.. Ofcourse i can avoid all of this by echoing under form error for empty form fields but that is not what i want...
In your original code $nameErr, $emailErr and $messageErr are changed after showing them.
If you make something like:
<?php $something = "value1";
echo $something;
$something = "value2";
?>
it will show value1 on the screen.
It should be something like this:
<?php
$nameErr='';
$emailErr='';
$messageErr= '';
if ($_POST) {
$name = $_POST['name'];
$email= $_POST['email'];
$message= $_POST['message'];
$formcontent= "From: $name \n Message: $message";
$recipient= "konstantin91#gmail.com";
$subject= "Contact Form";
$mailheader= "From: $email \r\n";
if(strlen($name)==0) {
$nameErr = "Name is required <br>";
}
elseif(strlen($email)==0) {
$emailErr = "Email is required";
}
elseif(strlen($message)==0) {
$messageErr = "Message is required <br>";
}
else {
echo "$name, thank you for submiting message";
}
}
?>
<form action="" method="POST">
<p>Name: <input type="text" name="name"><?php echo $nameErr; ?></p>
<p>Email: <input type="email" name="email"><?php echo $emailErr; ?></p>
<p>Message:</p> <textarea name="message" rows="10" cols="50"></textarea><br />
<p><?php echo $messageErr; ?></p>
<button type="submit" value="Submit" name="Submit1">Submit</button>
</form>
Also I removed die() because else it makes an exitbefore showing the error. However you don't needdie()here because it sends the form only if server runs the lastelse` statement, only if all fields are completed.

Some issue with my php contact form

I am trying to make a contact form using PHP and some issue is there. I am new to PHP so couldn't figured it out. The form works if there is no validation code applied but as I apply validation code so that some fields can be made necessary, the form doesn't works right. Moreover when I leave any required field empty then them form doesn't show any error message. Can someone please tell what the problem is.
HTML Form
<form action="mail.php" method="POST" >
Name: <input type="text" name="name"><br/><br/>
Email: <input type="email" name="email"><br/><br/>
Phone Number: <input type="text" name="phone_number"><br/><br/>
Website: <input type="text" name="website"><br/><br/>
Message: <textarea name="message" rows="6" cols="25"></textarea><br/><br/>
<input type="submit" value="Submit">
</form>
Main PHP Script File
<?php
if(isset ($_POST['submit'])) {
$errors = array();
if(!empty ($_POST ['name'])) {
$name = $_POST ['name'];
} else {
$errors[] = "You forgot to enter your Name.";
}
if(!empty ($_POST ['email'])) {
$email = $_POST ['email'];
} else {
$errors[] = "You forgot to enter your Email.";
}
if(!empty ($_POST ['message'])) {
$message = $_POST ['message'];
} else {
$errors[] = "You forgot to enter your Message.";
}
$phone_number = $_POST['phone_number'];
$website = $_POST['website'];
$formcontent = "From: $name \n Email: $email \n Phone Number: $phone_number \n Website: $website \n Message: $message";
$recipient = "yourmail#emial.com";
$subject = "Contact Form";
$mailheader = "From: $email \r\n";
mail($formcontent, $recipient, $subject, $mailheader);
if(isset($_POST['submit'])) {
if(!empty($errors)) {
foreach ($errors as $msg)
{
echo '<li>'. $msg . '</li>';
}
} else {
echo "Thank You";
}
}
}
?>
UPDATE
Thanks for your replies guys, I literally forgot to have name attribute for submit button. That helped for showing some result. But now some notices are showing for undefined variables as email, message (if I provide only name in form and hit submit button) for $formcontent and $mailheader lines.
There are a few things wrong with your code.
if(isset ($_POST['submit'])) you have no name attribute for the submit input to support that, therefore nothing inside that conditional statement will be executed.
Having used error reporting, would have thrown an "Undefined index submit..." warning/notice.
So you need to add one:
<input type="submit" value="Submit" name="submit">
^^^^^^^^^^^^^
Then you have your mail() parameters which are not in the right order.
mail($formcontent, $recipient, $subject, $mailheader);
which should be:
To:
Subject:
Message:
Headers
Change it to:
mail($recipient, $subject, $formcontent, $mailheader);
For more information on mail(), visit the following link on PHP.net:
http://php.net/manual/en/function.mail.php
Edit:
You also need to place mail() function in a different place, where you have your "Thank you". Otherwise, even if an email address is not entered in the form, the mail would still be sent out, thus showing as "unknown sender" in the From. Placing mail() in the else if no errors are found.
if(isset($_POST['submit'])) {
if(!empty($errors)) {
foreach ($errors as $msg)
{
echo '<li>'. $msg . '</li>';
}
} else {
mail($recipient, $subject, $formcontent, $mailheader);
echo "Thank You";
}
}
Add error reporting to the top of your file(s) which will help find errors.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
// rest of your code
Sidenote: Error reporting should only be done in staging, and never production.
You can also add Anti-spam to your form
$q1 = mt_rand(1,10);
$q2 = mt_rand(1,10);
$answer = $q1 + $q2;
<form action="mail.php" method="POST" >
Name: <input type="text" name="name"><br/><br/>
Email: <input type="email" name="email"><br/><br/>
Phone Number: <input type="text" name="phone_number"><br/><br/>
Website: <input type="text" name="website"><br/><br/>
Message: <textarea name="message" rows="6" cols="25"></textarea><br/><br/>
*What is <?php echo $q1 ." + ". $q2;?>? (Anti-spam):
<input type="number" required name="Human" ><br>
<!--question-->
<input name="answer" id="subject" type="hidden" value="<?php echo "$answer"; ?>">
<input type="submit" value="Submit">
</form>
in your form you can check if the answer is correct
<?php
$answer = $_POST['answer'];
if(isset ($_POST['submit']) && $_POST['human'] == answer) {
your mail procesing here
}

My PHP form submits but does not validate the email address

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

Script should send an email containing form submission values, but no email is getting sent

So I have a HTML form with some PHP but I'm not getting any email whatsoever after submitting it. I can't find the problem! can you help me out?
Tried changing the if(isset($_POST['submit'])) { to 'enviar' but still not working.
tried putting some echos to see where it's not working. the only statement that is stopping at the else statement is stripslashes.
The form snippet:
<div id="contact-wrapper">
<?php if(isset($hasError)) { //If errors are found ?>
<p class="error">Please check if you entered valid information.</p>
<?php } ?>
<?php if(isset($emailSent) && $emailSent == true) { //If email is sent ?>
<p><strong>Email sent with success!</strong></p>
<p>Thank you for using our contact form <strong><?php echo $name;?></strong>, we will contact you soon.</p>
<?php } ?>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" id="contactform">
<div>
<label for="name"><strong>Name:</strong></label>
<input type="text" size="50" name="contactname" id="contactname" value="" class="required" />
</div>
<div>
<label for="email"><strong>E-mail:</strong></label>
<input type="text" size="50" name="email" id="email" value="" class="required email" />
</div>
<div>
<label for="subject"><strong>Subject:</strong></label>
<input type="text" size="50" name="subject" id="subject" value="" class="required" />
</div>
<div>
<label for="message"><strong>Message:</strong></label>
<textarea rows="5" cols="50" name="message" id="message" class="required"></textarea>
</div>
<input type="submit" value="enviar" name="submit" id="submit" />
</form>
</div>
and the PHP:
<?php
//If the form is submitted
if(isset($_POST['submit'])) {
//Check to make sure that the name field is not empty
if(trim($_POST['contactname']) == '') {
$hasError = true;
} else {
$name = trim($_POST['contactname']);
}
//Check to make sure that the subject field is not empty
if(trim($_POST['subject']) == '') {
$hasError = true;
} else {
$subject = trim($_POST['subject']);
}
//Check to make sure sure that a valid email address is submitted
if(trim($_POST['email']) == '') {
$hasError = true;
} else if (!eregi("^[A-Z0-9._%-]+#[A-Z0-9._%-]+\.[A-Z]{2,4}$", trim($_POST['email']))) {
$hasError = true;
} else {
$email = trim($_POST['email']);
}
//Check to make sure comments were entered
if(trim($_POST['message']) == '') {
$hasError = true;
} else {
if(function_exists('stripslashes')) {
$comments = stripslashes(trim($_POST['message']));
} else {
$comments = trim($_POST['message']);
}
}
//If there is no error, send the email
if(!isset($hasError)) {
$emailTo = 'myemail#email.com'; //Put your own email address here
$body = "Name: $name \n\nEmail: $email \n\nSubject: $subject \n\nComments:\n $comments";
$headers = 'From: My Site <'.$emailTo.'>' . "\r\n" . 'Reply-To: ' . $email;
mail($emailTo, $subject, $body, $headers);
$emailSent = true;
}
}
?>
Before getting any email, you have to be sure the email is being sent.
$sent = mail($emailTo, $subject, $body, $headers);
var_dump($sent);
What does this code output when placed in the appropriate place?
Have you tried a simple php page to do a test Email (eg fixed content) and I assume the webserver has email configured and is prepared to relay for your address?
If this is WordPress contact form, for starters:
mail($emailTo, $subject, $body, $headers);
should be:
wp_mail($emailTo, $subject, $body, $headers);
See: wp_mail codex
Now you have to check your e-mail setup, as well as WordPress e-mail setup too.

HTML/PHP form not sending email

I have a form which does everything right except send the input values to my email, what am I doing wrong? Ps: not using local server, so that's not it.
EDIT: I'm not getting any email whatsoever.
Tried changing the if(isset($_POST['enviar'])) { part but still not working.
Tried the chatty echos. the only if statement that isn't behaving properly is stripslashes. It stops at the else statement.
The form snippet:
<div id="contact-wrapper">
<?php if(isset($hasError)) { //If errors are found ?>
<p class="error">Please check if you entered valid information.</p>
<?php } ?>
<?php if(isset($emailSent) && $emailSent == true) { //If email is sent ?>
<p><strong>Email sent with success!</strong></p>
<p>Thank you for using our contact form <strong><?php echo $name;?></strong>, we will contact you soon.</p>
<?php } ?>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" id="contactform">
<div>
<label for="name"><strong>Name:</strong></label>
<input type="text" size="50" name="contactname" id="contactname" value="" class="required" />
</div>
<div>
<label for="email"><strong>E-mail:</strong></label>
<input type="text" size="50" name="email" id="email" value="" class="required email" />
</div>
<div>
<label for="subject"><strong>Subject:</strong></label>
<input type="text" size="50" name="subject" id="subject" value="" class="required" />
</div>
<div>
<label for="message"><strong>Message:</strong></label>
<textarea rows="5" cols="50" name="message" id="message" class="required"></textarea>
</div>
<input type="submit" value="enviar" name="submit" id="submit" />
</form>
</div>
and the PHP:
<?php
//If the form is submitted
if(isset($_POST['submit'])) {
//Check to make sure that the name field is not empty
if(trim($_POST['contactname']) == '') {
$hasError = true;
} else {
$name = trim($_POST['contactname']);
}
//Check to make sure that the subject field is not empty
if(trim($_POST['subject']) == '') {
$hasError = true;
} else {
$subject = trim($_POST['subject']);
}
//Check to make sure sure that a valid email address is submitted
if(trim($_POST['email']) == '') {
$hasError = true;
} else if (!eregi("^[A-Z0-9._%-]+#[A-Z0-9._%-]+\.[A-Z]{2,4}$", trim($_POST['email']))) {
$hasError = true;
} else {
$email = trim($_POST['email']);
}
//Check to make sure comments were entered
if(trim($_POST['message']) == '') {
$hasError = true;
} else {
if(function_exists('stripslashes')) {
$comments = stripslashes(trim($_POST['message']));
} else {
$comments = trim($_POST['message']);
}
}
//If there is no error, send the email
if(!isset($hasError)) {
$emailTo = 'myemail#email.com'; //Put your own email address here
$body = "Name: $name \n\nEmail: $email \n\nSubject: $subject \n\nComments:\n $comments";
$headers = 'From: My Site <'.$emailTo.'>' . "\r\n" . 'Reply-To: ' . $email;
mail($emailTo, $subject, $body, $headers);
$emailSent = true;
}
}
?>
The ereg() family of functions are deprecated. use the preg_...() equivalents instead. They work almost exactly the same, except requiring delimiters around the match patterns.
As well, don't use PHP_SELF in your form. That value is raw user-supplied data and can be trivially subverted for an XSS attack.
Checking for a particular form field to see if a POST occured is somewhat unreliable - you might change the field's name later on and your check will fail. However, this
if ($_SERVER['REQUEST_METHOD'] == 'POST) { ... }
will always work, no matter how many or few fields are in the form, as long as the form was actually POSTed.
As for the actual problem, I'm assuming the mail is getting sent out, or you'd have complained about that. That means your variables aren't being populated properly. Instead of just sending the mail, echo out the various variables as they're built, something like:
echo 'Checking name';
if ($_POST['name'] .....) {
echo 'name is blank';
} else {
$name = ...;
echo "Found name=$name";
}
Basically have your code become extremely "chatty" and tell you what it's doing at each stage.
#dafz: Change
if(isset($_POST['submit'])) {
to
if(isset($_POST['enviar'])) {
#Marc B deserves another up-vote for his answer as well.
Edit
You can try the following update.
if(!isset($hasError)) {
$siteAddress = 'validaddress#yourdomain.com'; //Put admin# or info# your domain here
$emailTo = 'myemail#email.com'; //Put your own email address here
$body = "Name: $name \r\nEmail: $email \r\nSubject: $subject \r\nComments: $comments \r\n";
$headers = 'To: ' . $name . ' <' . $emailTo . '>' . "\r\n";
$headers .= 'From: My Site <' . $siteAddress . '>' . "\r\n";
$headers .= 'Reply-To: ' . $email . "\r\n";
if (mail($emailTo, $subject, $body, $headers)) {
$emailSent = true;
} else {
$emailSent = false;
}
}

Categories