php form not validatin or sending mails - php

I a trying to fix a php form that doesn't work
I am new to php, please help
I have the form in the index.html file and have another validation.php to validate the form fields.
<!-- contact form --->
<div class="containerq">
<div class="form_container">
<h2 class="text-center">Contact us</h2>
<form action="index.php" method="post" class="rd-mailform">
<input type="hidden" value="contact" name="form-type">
<fieldset>
<div class="row">
<div class="col-md-prefix-1 col-md-12">
<label data-add-placeholder="" class="mfInput">
<input type="text" name="name" placeholder="Name">
</label>
</div>
<div class="col-md-prefix-1 col-md-12">
<label data-add-placeholder="" class="mfInput">
<input type="text" name="email" placeholder="Email">
</label>
</div>
<div class="col-md-prefix-1 col-md-12">
<label data-add-placeholder="" class="mfInput">
<input type="text" name="phone" placeholder="Phone">
</label>
</div>
<div class="col-md-prefix-1 col-md-12">
<label data-add-placeholder="" class="mfSelect">
<select class="opt">
<option>Choose subject</option>
<option>I have a problem with a game</option>
<option>I have a problem with a course</option>
<option>I have an Idea</option>
<option>Collaboration with schools</option>
<option>Collaboration with game developers</option>
<option>General query and other subjects</option>
</select>
<ul class="dropdown">
<li class="option">I have a problem with a game</li>
<li class="option">I have a problem with a course</li>
<li class="option">I have an Idea</li>
<li class="option">Collaboration with schools</li>
<li class="option">Collaboration with game developers</li>
<li class="option">General query and other subjects</li>
</ul><span class="mfPlaceHolder"></span>
</label>
</div>
<div class="col-md-prefix-1 col-md-12">
<label data-add-placeholder="" class="mfInput">
<textarea data-constraints="" name="message" placeholder="Message" class="mtext"></textarea>
</label>
</div>
<!--<input class="header_button" type="submit" name="submit" value="Send Request">-->
<div class="header_button">Send Request </div>
<span class="success"><?php echo $successMessage;?></span>
<div class="mfInfo mfProgress"><span class="cnt"></span><span class="loader"></span><span class="msg"></span></div>
</div>
</fieldset>
</form>
</div>
</div>
in the header (which is in included at the index.php start) I added:
<?php require_once "validation.php";?>
because if I put require_once validation.php at the start of the index the form wouldn't be accessed.
in the validation.php this is the part that sends the mail:
if( !($name=='') && !($email=='') && !($phone=='') &&!($message=='') )
{ // Checking valid email.
if (preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/",$email))
{
$header= $name."<". $email .">";
$headers = "mywebsite.com"; /* Let's prepare the message for the e-mail */
$msg = "Hello! $name Thank you...! For Contacting Us.
Name: $name
E-mail: $email
Phone: $phone
Message: $message
This is a Contact Confirmation mail. We Will contact You as soon as possible.";
$msg1 = " $name Contacted Us. Hereis some information about $name.
Name: $name
E-mail: $email
Phone: $phone
Message: $message "; /* Send the message using mail() function */
if(mail($email, $headers, $msg ) && mail("receiver_mail_id#mywebsite.com", $header, $msg1 ))
{
$successMessage = "Message sent successfully.......";
}
}
else
{
$emailError = "Invalid Email";
}
}
but id doesn't send anything
the page gets reloaded to index.php#
I don't get the invalid email or Message sent successfully messages either
this is the complete validation.php:
<?php // Initialize variables to null.
//echo "validating";
$name =""; // Sender Name
$email =""; // Sender's email ID
$purpose =""; // Subject of mail
$message =""; // Sender's Message
$phone ="";
$nameError ="";
$emailError ="";
$phoneError ="";
$messageError ="";
$successMessage =""; // On submittingform below function will execute.
if(isset($_POST['submit']))
{ // Checking null values in message.
echo "validating2";
if (empty($_POST["name"])){
$nameError = "Name is required";
}
else
{
$name = test_input($_POST["name"]); // check name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$name))
{
$nameError = "Only letters and white space allowed";
}
} // Checking null values inthe message.
if (empty($_POST["email"]))
{
$emailError = "Email is required";
}
else
{
$email = test_input($_POST["email"]);
} // Checking null values inmessage.
if (empty($_POST["phone"]))
{
$phoneError = "Phone is required";
}
else
{
$phone = test_input($_POST["phone"]);
} // Checking null values inmessage.
if (empty($_POST["message"]))
{
$messageError = "Message is required";
}
else
{
$message = test_input($_POST["message"]);
} // Checking null values inthe message.
if( !($name=='') && !($email=='') && !($phone=='') &&!($message=='') )
{ // Checking valid email.
if (preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/",$email))
{
$header= $name."<". $email .">";
$headers = "mywebsite.com"; /* Let's prepare the message for the e-mail */
$msg = "Hello! $name Thank you...! For Contacting Us.
Name: $name
E-mail: $email
Phone: $phone
Message: $message
This is a Contact Confirmation mail. We Will contact You as soon as possible.";
$msg1 = " $name Contacted Us. Here is some information about $name.
Name: $name
E-mail: $email
Phone: $phone
Message: $message "; /* Send the message using mail() function */
if(mail($email, $headers, $msg ) && mail("contact#mywebsite.com", $header, $msg1 ))
{
$successMessage = "Message sent successfully.......";
}
}
else
{
$emailError = "Invalid Email";
}
}
} // Function for filtering input values.function test_input($data)
// Function for filtering input values.
function test_input($data)
{
$data = trim($data);
$data =stripslashes($data);
$data =htmlspecialchars($data);
return $data;
}
?>
any ideas?

Related

HTML5 Contact form is submitting without any data in fields

My first time posting here so apologies if i get anything wrong. I have recently built a site from a HTML5 UP template - www.vancareleeds.co.uk. I have used the contact form that came with the template and used a simple mail.php file in the root folder to action the email to be sent to my inbox.
I have also put in Google ReCaptcha but am since struggling to force the form to validate (EG. the form can be sent without the reCaptcha being ticked and it can also be sent with no information in the fields on the form.
I have provided my code here of the .php and also the webpage itself.
If i have broken protocol or best practice for psots i apologise.
mail.php
<?php $name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$mobile = $_POST['mobile'];
$vehicle = $_POST['category-vehicle'];
$service = $_POST['category-service'];
$formcontent="From: $name \n Message: $message \n Mobile: $mobile \n Vehicle: $vehicle \n Service Required: $service";
$recipient = "info#vancareleeds.co.uk";
$subject = "Contact Form from VanCare Website";
$mailheader = "From: $email \r\n";
mail($recipient, $subject, $formcontent, $mailheader) or die("Error!");
echo "Thank You!";
?>
form html
<form method="post" action="mail.php">
<div class="field">
<label for="name">Name</label>
<input type="text" name="name" id="name" />
</div>
<div class="field">
<label for="email">Email</label>
<input type="email" name="email" id="email" />
</div>
<div class="field">
<label for="message">Message</label>
<textarea name="message" id="message" rows="4"></textarea>
</div>
<div class="g-recaptcha" data-theme="dark" class="g-recaptcha" data-sitekey="6Lf1OVMUAAAAAJv1fNtt-CJEFPK-Q0Ugc1CVCRVh"></div><br/>
<ul class="actions">
<li><input type="submit" value="Send Message" /></li>
</ul>
</form>
Welcome +Catalan Soccer! I would suggest to you if you are new to PHP to use var_dump(), print_r() or var_export() the result of the $_POST global array to see what was sent to your PHP script. All other things you can comment out and uncomment if you feel confident.
$errors = [];
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['name'], $_POST['email'], $_POST['message']) === true) {
$name = filter_var(trim($_POST['name']), FILTER_SANITIZE_STRING);
if (empty($name) === true) {
$errors['name'][] = 'Name is empty';
} elseif (ctype_alpha($name) === false) {
$errors['name'][] = 'Name contains invalid characters';
}
$email = filter_var(trim($_POST['email']), FILTER_SANITIZE_EMAIL);
if (empty($email) === true) {
$errors['email'][] = 'E-mail is empty';
} elseif ($email === false) {
$errors['email'][] = 'Invalid e-mail address';
}
$message = strip_tags(trim($_POST['message']));
if (empty($message) === true) {
$errors['message'][] = 'Message is empty';
}
if (count($errors) === 0) {
echo 'Thank you!';
// you can use here the sanitized user input to send the e-mail
}
}
if (count($errors) > 0) {
foreach ($errors as $field => $messages) {
echo implode(', ', $messages), '<br>';
}
}
This will test user input and print out error message.

Dynamic form validation between an HTML and PHP file. Is this possible?

Currently on my site JorgeGoris.com I have a form that is pointing to a php file called form_process.php for validation. My problem is that I never see the validation or success messages I have implemented take place because when I hit submit I am redirected to form_process.php I want this to take place dynamically in the same page. How can I do this? This is my form and php code:
<?php
// define variables and set to empty values
$firstName_error = $email_error = $phone_error = "";
$firstName = $lastName = $email = $phone = $message = $success = "";
//form is submitted with POST method
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["firstname"])) {
$firstName_error = "First name is required";
} else {
$firstName = test_input($_POST["firstname"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$firstName)) {
$firstName_error = "Only letters and white space allowed";
}
}
if (empty($_POST["email"])) {
$email_error = "Email is required";
} else {
$email = test_input($_POST["email"]);
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$email_error = "Invalid email format";
}
}
if (empty($_POST["phone"])) {
$phone_error = "Phone is required";
} else {
$phone = test_input($_POST["phone"]);
// check if e-mail address is well-formed
if (!preg_match("/^(\d[\s-]?)?[\(\[\s-]{0,2}?\d{3}[\)\]\s-]{0,2}?\d{3}[\s-]?\d{4}$/i",$phone)) {
$phone_error = "Invalid phone number";
}
}
if (empty($_POST["message"])) {
$message = "";
} else {
$message = test_input($_POST["message"]);
}
if ($firstName_error == '' and $email_error == '' and $phone_error == '' ){
$message_body = '';
unset($_POST['submit']);
foreach ($_POST as $key => $value){
$message_body .= "$key: $value\n";
}
$to = 'J_goris#live.com';
$subject = 'Potential Client/Employer-JorgeGoris';
if (mail($to, $subject, $message_body)){
$success = "Message sent, I'll get back to you shortly!";
$firstName = $email = $phone = $message = '';
echo "<h1>Got it! I'll get back to you shortly!</h1>";
}
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<form action="form_process.php" method="post" name="contact_form">
<div class="form-row">
<div class="col-lg-3 offset-lg-3 col-sm-12">
<input type="text" class="form-control" placeholder="First Name *" name="firstname">
<span class="error"><?php= $firstName_error ?></span>
</div><!--end col-->
<div class="col-lg-3 col-sm-12">
<input type="text" class="form-control" placeholder="Last Name" name="lastname">
</div><!--end col-->
</div><!--end row-->
<div class="form-row">
<div class="col-lg-3 offset-lg-3 col-sm-12">
<input type="text" class="form-control" placeholder="Phone Number" name="phone">
<span class="error"><?php= $phone_error ?></span>
</div><!--end col-->
<div class="col-lg-3 col-sm-12">
<input type="email" class="form-control" placeholder="Email *" name="email">
<span class="error"><?php= $email_error ?></span>
</div><!--end col-->
</div><!--end row-->
<div class="row">
<div class="col-lg-5 offset-lg-3 col-sm-12">
<textarea class="form-control" rows="5" placeholder="Tell me a little about your project. Budget details are also appreciated. *" name="message"></textarea>
</div><!--end col-->
</div><!--end row-->
<div class="success"><?php= $success; ?></div>
<button type="submit" class="button" name="submit">Submit</button>
</form><!--end form-->
The proper method to achieve the desired functionality is to have your form-data sent to the PHP file (or function) which is responsible for loading the form. The PHP code which loads the form should be conditional. For example you can have a check for errors in the submitted post-data and if there's an error some HTML code that displays the error should be outputted in addition to the normal HTML code of the form.
In your case you don't see anything when you hit the submit button because the PHP script to which your form is pointing doesn't output the HTML of the page that contains the form.

Php mail function sends email every time page is refreshed

I used the mail function to do a contact form and it all works fine. However, I just noticed that after sending an email, every time a refresh the page, even though the fields are empty, an email keeps being sent.
My code looks like this:
<form role="form" method="POST">
<br style="clear:both">
<h3 style="margin-bottom: 25px; text-align: center;">Contact a Conveyancing Property Lawyer Now</h3>
<div class="form-group">
<input type="text" class="form-control" id="name" name="name" placeholder="Name" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?> required>
</div>
<div class="form-group">
<input type="text" class="form-control" id="email" name="email" placeholder="Email" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?> required>
</div>
<div class="form-group">
<input type="text" class="form-control" id="mobile" name="mobile" placeholder="Contact Number" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?> required>
</div>
<div class="form-group">
<input type="text" class="form-control" id="subject" name="subject" placeholder="Subject" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?> required>
</div>
<div class="form-group">
<select name="situation" id="situation">
<option>Select Current Situation</option>
<option class="placeholder" value="Unemployed">Unemployed</option>
<option class="placeholder" value="Employed">Employed</option>
</select>
</div>
<button type="submit" id="submit" name="submit" class="btn btn-primary">Submit</button>
<?php
if (isset($_POST["submit"])) {
$name = $_POST['name'];
$email = $_POST['email'];
$mobile = $_POST['mobile'];
$subject_line = $_POST['subject'];
$situation = $_POST['situation'];
$from = 'myemail#email.co.za';
$to = 'myemail#email.co.za';
$subject = 'SchoemanLaw lead ...';
$body ="From: $name <br/> E-Mail: $email <br/> Mobile: $mobile Subject: $subject_line <br/> Situation: $situation";
//$body ="From: $name\r\n E-Mail: $email\r\n Mobile:\r\n $mobile Subject: $subject_line\r\n Situation:\r\n $situation";
// 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 optional/headers
$headers .= "From:$from";
// Check if name has been entered
if (!$_POST['name']) {
$errName = 'Please enter your name';
}
// Check if email has been entered and is valid
if (!$_POST['email'] || !filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
$errEmail = 'Please enter a valid email address';
}
// Check if mobile has been entered
if (!$_POST['mobile']) {
$errMobile = 'Please enter your number';
}
// If there are no errors, send the email
if (!$errName && !$errEmail && !$errMobile) {
if (mail($to,$subject,$body,$headers)) {
$result='<div class="alert alert-success">Thank You ! We will be in touch soon</div>';
echo $result;
} else {
$result='<div class="alert alert-danger">Sorry there was an error sending your message. Please try again later.</div>';
echo $result;
}
}
}
?>
</form>
How can I make the site forget all the details from the input fields once an email is sent?
I tried to follow this question here but I don't seem to be able to make it work on my site
The easiest way is to add an forwarding in your code, like that:
EDIT: at #CD001 commentary
if (mail($to,$subject,$body,$headers)) {
$result='<div class="alert alert-success">Thank You ! We will be in touch soon</div>';
echo $result;
// header('Location: ?successfull-submit'); exit; // this one would fail because above is an output.
echo '<meta http-equiv="refresh" content="0; url=?successfull-submit">'; // its not a good /nice alternative but it "works".
Redirect to ?sent=1 without sending any output. And check 'sent' to determine whether or not to display the success message. Try below (assuming your script is contact.php). Also make sure
contact.php
<?php
$result = '';
if (isset($_POST["submit"])) {
$name = $_POST['name'];
$email = $_POST['email'];
$mobile = $_POST['mobile'];
$subject_line = $_POST['subject'];
$situation = $_POST['situation'];
$from = 'myemail#email.co.za';
$to = 'myemail#email.co.za';
$subject = 'SchoemanLaw lead ...';
$body ="From: $name <br/> E-Mail: $email <br/> Mobile: $mobile Subject: $subject_line <br/> Situation: $situation";
//$body ="From: $name\r\n E-Mail: $email\r\n Mobile:\r\n $mobile Subject: $subject_line\r\n Situation:\r\n $situation";
// 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 optional/headers
$headers .= "From:$from";
// Check if name has been entered
if (!$_POST['name']) {
$errName = 'Please enter your name';
}
// Check if email has been entered and is valid
if (!$_POST['email'] || !filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
$errEmail = 'Please enter a valid email address';
}
// Check if mobile has been entered
if (!$_POST['mobile']) {
$errMobile = 'Please enter your number';
}
// If there are no errors, send the email
if (!$errName && !$errEmail && !$errMobile) {
if (mail($to,$subject,$body,$headers)) {
//$result='<div class="alert alert-success">Thank You ! We will be in touch soon</div>';
//echo $result;
header('Location:' . 'contact.php?sent=1');
exit;
} else {
$result='<div class="alert alert-danger">Sorry there was an error sending your message. Please try again later.</div>';
//echo $result;
}
}
}
if(isset($_GET['sent'])) {
$result='<div class="alert alert-success">Thank You ! We will be in touch soon</div>';
}
echo $result;
?>
<form role="form" method="POST">
<br style="clear:both">
<h3 style="margin-bottom: 25px; text-align: center;">Contact a Conveyancing Property Lawyer Now</h3>
<div class="form-group">
<input type="text" class="form-control" id="name" name="name" placeholder="Name" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?> required>
</div>
<div class="form-group">
<input type="text" class="form-control" id="email" name="email" placeholder="Email" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?> required>
</div>
<div class="form-group">
<input type="text" class="form-control" id="mobile" name="mobile" placeholder="Contact Number" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?> required>
</div>
<div class="form-group">
<input type="text" class="form-control" id="subject" name="subject" placeholder="Subject" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?> required>
</div>
<div class="form-group">
<select name="situation" id="situation">
<option>Select Current Situation</option>
<option class="placeholder" value="Unemployed">Unemployed</option>
<option class="placeholder" value="Employed">Employed</option>
</select>
</div>
<button type="submit" id="submit" name="submit" class="btn btn-primary">Submit</button>
</form>
try like this,in your success message part..
<?php
if (isset($_POST["submit"])) {
$name = $_POST['name'];
$email = $_POST['email'];
$mobile = $_POST['mobile'];
$subject_line = $_POST['subject'];
$situation = $_POST['situation'];
$from = 'myemail#email.co.za';
$to = 'myemail#email.co.za';
$subject = 'SchoemanLaw lead ...';
$body ="From: $name <br/> E-Mail: $email <br/> Mobile: $mobile Subject: $subject_line <br/> Situation: $situation";
//$body ="From: $name\r\n E-Mail: $email\r\n Mobile:\r\n $mobile Subject: $subject_line\r\n Situation:\r\n $situation";
// 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 optional/headers
$headers .= "From:$from";
// Check if name has been entered
if (!$_POST['name']) {
$errName = 'Please enter your name';
}
// Check if email has been entered and is valid
if (!$_POST['email'] || !filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
$errEmail = 'Please enter a valid email address';
}
// Check if mobile has been entered
if (!$_POST['mobile']) {
$errMobile = 'Please enter your number';
}
// If there are no errors, send the email
if (!$errName && !$errEmail && !$errMobile) {
if (mail($to,$subject,$body,$headers)) {
echo "<script>alert('Mail sent Successfully');</script>";
echo "<script>window.location = 'contact.php';</script>";
} else {
echo "<script>alert('Mail not sent');</script>";
echo "<script>window.location = 'contact.php';</script>";
}
}
}
?>
while redirect to another page you can restrict that duplication problem....
Just try redirecting to another page or another function that discards the old $_POST data.
You could use session variable and reset it after each request.
Or, prevent reloading same page using javascript.
Or, redirect to some other page upon completion (if possible)
You can try to add CSRF token to your page to prevent double submission.
Refer to this link: How to prevent multiple form submission on multiple clicks in PHP
When the user refreshes the page, it is possible that the same parameters are getting posted again. As a result, if (isset($_POST["submit"])) This condition becomes true and mail will be sent every time user reloads.
One solution is to redirect to the same page or to a different page on success full completion.
ie,
if (mail($to,$subject,$body,$headers)) {
$result='<div class="alert alert-success">Thank You ! We will be in touch soon</div>';
echo $result;
}
Instead of the above method, redirect user to the same page or different page and show a message there. If you want to show the same page you can redirect with a flag in the query string as ?show_success_msg= true.
Then do this.
if(isset($_GET['show_success_msg']) && $_GET['show_success_msg'] == 'true') {
$result='<div class="alert alert-success">Thank You ! We will be in touch soon</div>';
echo $result;
}
Complete solution here:
<?php
// Handle PHP code always on Top of the page (ie, Not after your HTML), You cant send headers if you have any content above it.
if (isset($_POST["submit"])) {
$name = $_POST['name'];
$email = $_POST['email'];
$mobile = $_POST['mobile'];
$subject_line = $_POST['subject'];
$situation = $_POST['situation'];
$from = 'myemail#email.co.za';
$to = 'myemail#email.co.za';
$subject = 'SchoemanLaw lead ...';
$body ="From: $name <br/> E-Mail: $email <br/> Mobile: $mobile Subject: $subject_line <br/> Situation: $situation";
//$body ="From: $name\r\n E-Mail: $email\r\n Mobile:\r\n $mobile Subject: $subject_line\r\n Situation:\r\n $situation";
// 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 optional/headers
$headers .= "From:$from";
// Check if name has been entered
if (!$_POST['name']) {
$errName = 'Please enter your name';
}
// Check if email has been entered and is valid
if (!$_POST['email'] || !filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
$errEmail = 'Please enter a valid email address';
}
// Check if mobile has been entered
if (!$_POST['mobile']) {
$errMobile = 'Please enter your number';
}
// If there are no errors, send the email
if (!$errName && !$errEmail && !$errMobile) {
if (mail($to,$subject,$body,$headers)) {
$result='<div class="alert alert-success">Thank You ! We will be in touch soon</div>';
echo $result;
} else {
header("Location: your_page.php?show_success_msg=true")
}
}
}
?>
<form role="form" method="POST">
<?php if(isset($_GET['show_success_msg']) && $_GET['show_success_msg'] ==
'true') {
$result='<div class="alert alert-success">Thank You ! We will be in touch
soon</div>';
echo $result;
} ?>
<br style="clear:both">
<h3 style="margin-bottom: 25px; text-align: center;">Contact a Conveyancing Property Lawyer Now</h3>
<div class="form-group">
<input type="text" class="form-control" id="name" name="name" placeholder="Name" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?> required>
</div>
<div class="form-group">
<input type="text" class="form-control" id="email" name="email" placeholder="Email" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?> required>
</div>
<div class="form-group">
<input type="text" class="form-control" id="mobile" name="mobile" placeholder="Contact Number" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?> required>
</div>
<div class="form-group">
<input type="text" class="form-control" id="subject" name="subject" placeholder="Subject" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?> required>
</div>
<div class="form-group">
<select name="situation" id="situation">
<option>Select Current Situation</option>
<option class="placeholder" value="Unemployed">Unemployed</option>
<option class="placeholder" value="Employed">Employed</option>
</select>
</div>
<button type="submit" id="submit" name="submit" class="btn btn-primary">Submit</button>

Change a field in PHP form from required to optional

I am a complete novice when it comes to PHP. I downloaded a form I found online to include in my Bootstrap site. It is a very simple form anyone can use to send me a message. I managed to set up Wamp to test out the PHP but when I leave the Phone field blank it gives me an error message telling me please go back and correct the error. I want to make it so if someone leaves out the phone number it still sends the email. Thank you.
HTML
<form name="contactform" method="post" action="index.php" class="form-vertical">
<div class="form-group">
<label for="inputName" class="control-label">Name</label>
<input type="text" class="form-control" id="inputName" name="inputName" placeholder="First and Last">
</div>
<div class="form-group">
<label for="inputEmail" class="control-label">Email*</label>
<input type="text" class="form-control" id="inputEmail" name="inputEmail" placeholder="Required">
</div>
<div class="form-group">
<label for="inputPhone" class="control-label">Phone Number</label>
<input type="text" class="form-control" id="inputPhone" name="inputPhone" placeholder="Optional">
</div>
<div class="form-group">
<label for="inputMessage" class="control-label">Message</label>
<textarea class="form-control" rows="5" id="inputMessage" name="inputMessage" placeholder="Brief Description"></textarea>
</div>
<div class="form-group">
<button type="submit" class="btn btn-custom pull-right hvr-underline-from-left">Send</button>
</div>
</form>
PHP
<?php
/* Set e-mail recipient */
$myemail = "myaccount#gmail.com";
/* Check all form inputs using check_input function */
$name = check_input($_POST['inputName'], "First and Last");
$email = check_input($_POST['inputEmail'], "Required");
$phone = check_input($_POST['inputPhone'], "Optional");
$message = check_input($_POST['inputMessage'], "Brief Description");
/* If e-mail is not valid show error message */
if (!preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/", $email)) {
show_error("Invalid e-mail address");
}
/* Let's prepare the message for the e-mail */
$subject = "Contact Message from mywebsite.net";
$message = "
Someone has sent you a message using your contact form:
Name: $name
Email: $email
Phone: $phone
Message:
$message
";
/* Send the message using mail() function */
mail($myemail, $subject, $message);
/* Redirect visitor to the thank you page */
header('Location:contact.html');
exit();
/* Functions we used */
function check_input($data, $problem='')
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
if ($problem && strlen($data) == 0)
{
show_error($problem);
}
return $data;
}
function show_error($myError)
{
?>
<html>
<body>
<p>Please correct the following error:</p>
<strong><?php echo $myError; ?></strong>
<p>Hit the back button and try again</p>
</body>
</html>
<?php
exit();
}
?>
Please change this line:
$phone = check_input($_POST['inputPhone'], "Optional");
to:
$phone = check_input($_POST['inputPhone']);
This way show_error($problem); won't be called.
Because function check_input include function show_error.
And function show_error have exit() when have errors.
So, your phone input == NULL => so have error and call to exit().
Solution for this case
Don't check require with phone number input.
PHP
<?php
function show_error($myError)
{
?>
<html>
<body>
<p>Please correct the following error:</p>
<strong><?php echo $myError; ?></strong>
<p>Hit the back button and try again</p>
</body>
</html>
<?php
exit();
}
/* Functions we used */
function check_input($data, $problem='')
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
if ($problem && strlen($data) == 0)
{
show_error($problem);
}
return $data;
}
/* Set e-mail recipient */
$myemail = "myaccount#gmail.com";
/* Check all form inputs using check_input function */
$name = check_input($_POST['inputName'], "First and Last");
$email = check_input($_POST['inputEmail'], "Required");
$phone = $_POST['inputPhone'];
$message = check_input($_POST['inputMessage'], "Brief Description");
/* If e-mail is not valid show error message */
if (!preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/", $email))
{
show_error("Invalid e-mail address");
}
/* Let's prepare the message for the e-mail */
$subject = "Contact Message from mywebsite.net";
$message = "
Someone has sent you a message using your contact form:
Name: $name
Email: $email
Phone: $phone
Message:
$message
";
/* Send the message using mail() function */
mail($myemail, $subject, $message);
/* Redirect visitor to the thank you page */
header('Location:contact.html');
exit();
?>
You are facing this error because you are validating the phone number i.e $_POST['inputPhone'] using the check_input function in the line
$phone = check_input($_POST['inputPhone'], "Optional");
You can avoid this error in multiple ways:
$phone = $_POST['inputPhone']; //not secure
OR
$phone = check_input($_POST['inputPhone'], "");
OR
$phone = filter_var($_POST['inputPhone'],FILTER_SANITIZE_STRIPPED);

PHP form , showing message after submission

I am making a PHP form and not sure how to go about having the code say "message delivered" when clicking submission and having it validate correctly. Here is my code so far. I realize that the message appears anytime you click submit. Thank you for your patience.
<?php
// define variables and set to empty values
$nameErr = $emailErr = $genderErr = $websiteErr = "";
$name = $email = $comment = $message = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["name"]);
}
if (empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email = test_input($_POST["email"]);
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}
}
if (empty($_POST["comment"])) {
$comment = "";
} else {
$comment = test_input($_POST["comment"]);
}
if (isset($_POST["submit"])) {
$message = "Message has been delivered";
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<div class="cntr">
<h2>Contact Form</h2>
<p><span class="error">* required field.</span></p>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<div class="field">
<label for="name">Name </label>
<br>
<input type="text" name="name">
<span class="error">*<?php echo $nameErr;?></span>
</div>
<div class="field">
<label for="email">Email</label>
<br>
<input type="text" name="email">
<span class="error">* <?php echo $emailErr;?></span>
</div>
<div class="field">
<label for="message">Message</label>
<br>
<textarea name="comment" rows="8" cols="40"></textarea>
</div>
<button type="submit" class="email" name="submit" value="Submit">Submit</button>
<?php echo $message; ?><br/>
</form>
</div>
Use
if (isset($_POST["submit"]) && empty($nameErr) && empty($genderErr) && empty($emailErr) && empty($websiteErr)) {
$message = "Message has been delivered";
}
instead of
if (isset($_POST["submit"])) {
$message = "Message has been delivered";
}
Because isset($_POST["submit"]) is true when ever you do a submit , so you need to check the error variables are empty also . if the error variables are empty that means your code validated and passed .

Categories