PHP Form Only Submitting Emails From Gmail and No Other Addresses - php

I have an html from. When the user submits the form, I'm sending an email to the given email address using php. Emails to gmail accounts go through perfectly fine. However, mails to providers like yahoo, aol etc does not go through.There is no filter mechanism in my code to filter out email addresses. Some mails to yahoo mail addresses goes through rarely. But aol doesn't go at all. What is the issue here?
My html code:
<section class="contact-container">
<div class="container mtb">
<div class="row">
<div class="col-md-8 wow fadeInLeft">
<h4>Get in touch</h4>
<hr>
<p>Leave a comment, review, or general musings.
</p><br/>
<form method="post" id="captcha_form" name=
"captcha_form" action="mailform.php"><fieldset><ol>
</li><li><label class="solo" for="email">Email address:</label>
<span class="required">(required)</span><input type="text" class="solo
input" name="email" id="email" value="" />
</li><li><label class="solo" for="name">Name:</label><input type=
"text" class="solo input" name="name" id="name" value="" />
</li><li><label class="solo" for="subject">Subject:</label>
<span class="required">(required)</span> <input type="text" class=
"solo input" name="subject" id="subject" />
</li><li><label class="solo" for="message">Message:</label>
<span class="required">(required)</span>
<div class="solo input"><textarea class="solo input" name="message" id=
"message" ></textarea><br />
<p><input name="submit" id="submit" type="submit" value="Send" style=
"float: right;" /></p></div>
</li></ol>
</fieldset></form> <br /> <br />
</div>
And here is snippets of mailform.php:
<?php
$dontsendemail = 0;
$possiblespam = FALSE;
$strlenmessage = "";
$email = $_REQUEST['email'];
$message = $_REQUEST['message'];
$subject = $_REQUEST['subject'];
$emailaddress = "email#gmail.com";
/ Check human test input box
if(isset($_REQUEST["htest"]) && $_REQUEST["htest"] != "") die
("Possible spam detected. Please hit your browser back button
and check your entries.");
// Check email address function
function checkemail($field) {
// checks proper syntax
if( !preg_match( "/^([a-zA-Z0-9])+([a-zA-Z0-9._-])*#([a-zA-Z0-9_-])+
([a-zA-Z0- 9._-]+)+$/", $field))
{
die("Improper email address detected. Please hit your browser back
button and enter a proper email address.");
return 1;
}
}
// Spamcheck function
function spamcheck($field) {
if(preg_match("/to:/i",$field) || preg_match("/cc:/i",$field)
|| preg_match("/\r/i",$field) || preg_match("/i\n/i",$field)
|| preg_match("/%0A/i",$field)){
$possiblespam = TRUE;
}else $possiblespam = FALSE;
if ($possiblespam) {
die("Possible spam attempt detected. If this is not the case, please
editthe content of the contact form and try again.");
return 1;
}
}
if ($dontsendemail == 0) {
$message="";
$message.="Name: ".$name."\r\n";
$message.="Mailing Address: \r\nLine 1: ".$addressline1."\r\nLine
2: ".$addressline2."\r\nCity: ".$city."\r\nState: ".$state."
\r\nZip: ".$zip."\r\n";
$message=$message."\r\nMessage:\r\n".$_REQUEST['message'];
mail($emailaddress,"$subject",$message,"From: $email" );
include "email_sent.php";
echo "Thank you, I will respond shortly.";
}

Don't use a regex to confirm email addresses. The real regex is like a day long. Use http://www.w3schools.com/php/filter_validate_email.asp or https://code.google.com/p/php-smtp-email-validation/ or https://github.com/appskitchen/emailverifier/blob/master/class.emailverify.php . You'll notice they are much more complicated than a basic regex. The email spec is insane: https://www.rfc-editor.org/rfc/rfc2822

Related

Form validation in php - the error and success message display at the same time

I'm learning coding and created a simple form where error messages are
displayed just below each input field. However, when I check the form
the success message appears at the same time as error messages instead
of displaying when all the fields are correctly entered and form
validated. Can you please help. Thank yo in advance. Here is my
code.
</php>
$errorMessage = "";
$successMessage = "";
$emailError = "";
$emailconfirmError = "";
$nameError = "";
$messageError = "";
$servicesError = "";
$name = $email = $emailConfirm = $services = $message = "";
$email = isset($_POST['email']) ? $_POST['email'] : '';
$emailConfirm = isset($_POST['emailConfirm']) ? $_POST['emailConfirm'] : '';
if ($_POST) {
if (!$_POST['email']) {
$emailError .="The email is required";
}
if (!$_POST['emailConfirm']) {
$emailconfirmError .="Please confirm your email <br>";
}
if ($_POST['emailConfirm'] && $email != $emailConfirm) {
$emailconfirmError .="The email addresses do not match <br>";
}
if (!$_POST['name']) {
$nameError .="The name field is required <br>";
}
if (!$_POST['services']) {
$servicesError .="Please select a service required <br>";
}
if (!$_POST['message']) {
$messageError .="The message field is required <br>";
}
if ($_POST['email'] && filter_var($_POST['email'], FILTER_VALIDATE_EMAIL) === false) {
$emailError .= "The email address is invalid.<br>";
}
if ($name = $email = $emailConfirm = $services = $message != "") {
echo $emailError;
echo $emailconfirmError;
echo $name;
echo $services;
echo $message;
}else {
$emailTo = "kamala_guliyeva#hotmail.com";
$services = $_POST['services'];
$message = $_POST['message'];
$headers = "From: ".$_POST['email'];
if (mail($emailTo, $services, $message, $headers)) {
$successMessage = '<div class="alert alert-success" role="alert">Thank you for your message. We\'ll get back to you ASAP!</div>';
} else {
$errorMessage = '<div class="alert alert-danger" role="alert"><p>Your message couldn\'t be sent - please try again</div>';
}
}
}
and HTML
<div id="quote">
<div class="container">
<h2 class="section-title">Request a Quote</h2>
<hr align="left" width="8%" class="style-one">
<br>
<div><? echo $errorMessage.$successMessage; ?></div>
<form id="quoteForm" method="post">
<div class="row">
<div class="col-md-6">
<div class="form-group">
<input type="email" class="form-control" style="height:60px" id="email" name="email" placeholder="Your email">
<label class="error" id="emailError"><?php echo $emailError; ?></label>
</div>
<div class="form-group">
<input type="email" class="form-control" style="height:60px" id="emailConfirm" name="emailConfirm" placeholder="Re-type your email">
<label class="error" for="e-mailConfirm" id="emailconfirmError"><?php echo $emailconfirmError; ?></label>
</div>
<div class="form-group">
<input type="name" class="form-control" id="name" style="height:60px" name="name" placeholder="Your Name">
<label class="error" for="name" id="nameError"><?php echo $nameError; ?></label>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<select class="form-control" id="services" name="services" style="height:60px">
<option value="">Select Services</option>
<option value="Installation">Installation</option>
<option value="Repair">Repair</option>
<option value="Service and Maintenance">Service and Maintenance</option>
</select>
<label class="error" for="services" id="servicesError"><?php echo $servicesError; ?></label>
</div>
<div class="form-group">
<textarea class="form-control" id="message" name="message" placeholder="Message" style="height: 163px;" cols="35"></textarea>
<label class="error" for="message" id="messageError"><?php echo $messageError; ?></label>
</div>
</div>
</div>
<div class="form-row text-center">
<div class="col-12">
<button type="submit" style="width:10rem" class="btn quoteButton pt-3 pb-3 text-align-center">Get a Quote</button>
</div>
</div>
</form>
</div>
</div>
You've a few problems there...
So first thing is how you are doing your checks.
if(!$_POST) {
is not a valid way of checking that a post has occurred you need to do something like
if(isset($_POST) && !empty($_POST)) {
would be more appropriate as you are checking if the POST array is actually set and then that it is not empty the && operator is a short circuit operator so if either condition isn't met then the check will fail.
Similarly on your comparisons saying if(!$_POST['email']) { isn't valid because you're effectively asking "if the email part of the post array is not true" where as you need to be asking "if it's not blank and is a valid email address"
You need to be aware of the difference between = == and === operators. You can find some more information here: The 3 different equals
And also the filter_var function here: http://php.net/manual/en/function.filter-var.php
if($_POST['email']!=="" && filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
//all good
} else {
//set your error message
}
you can use regular expressions to validate 'name' see preg_match in the manual http://php.net/manual/en/function.preg-match.php
Aside from all of this if you want to have real time monitoring of the fields and the error messages etc you're going to have to look at incorporating Javascript and using AJAX to communicate with your script and then parse the response back into the appropriate div.
Have a look at Rasmus 30 second AJAX tutorial will give you a starting point for this http://rajshekhar.net/blog/archives/85-Rasmus-30-second-AJAX-Tutorial.html
However it is better practice to do both client and server side validation hope this helps even if it is not a complete answer per sé.

PHP - Display error message inside text field if form fails validation

Hi please excuse the rookie question as I am still very much learning PHP. Im trying to do a basic form validation. Im trying to get any errors found upon validation to be displayed in red inside the form field. If no errors are found the form should redirect to a Thank you page.
Ive written a basic validation, but I am now stuck on how to correctly implement it.
My question is:
How do I get the error messages to display inside the form field WITHOUT sending the form?
How do I procees to send the form if no errors is found?
My code follows:
HTML
<form id="enquire" method="post" action="thankyou.php">
<h2>Test Drive an Audi Today</h2>
<input type="text" value="Name" class="textbox" id="name" name="name" onfocus="if(this.value=='Name') this.value='';" /><br />
<br />
<input type="text" value="Surname" class="textbox" id="surname" name="surname" onfocus="if(this.value=='Surname') this.value='';" /><br />
<br />
<input type="text" value="Contact Number" class="textbox" id="nr" name="nr" onfocus="if(this.value=='Contact Number') this.value='';" /> <br />
<br />
<input type="text" value="Email" class="textbox" id="email" name="email"onfocus="if(this.value=='Email') this.value='';" /><br />
<br />
<select id="swapImg" name="model" class="modelSelect" onchange="swapImage()" >
<option value="images/1.jpg">A4</option>
<option value="images/2.jpg" selected="selected">A6</option>
<option value="images/3.jpg">A8</option>
</select>
<br />
<br />
<input type="submit" name="submit" class="butt" value="Send" />
<span class="buttonText">We'll Call you Back!</span>
</form>
PHP
if (isset($_POST['enquire'])){
//condition
$correct = false;
//Get Info
$name = $_POST['name'];
$surname = $_POST['surname'];
$number = $_POST['nr'];
$email = $_POST['email'];
$_REQUEST['model'];
//name fields
$string_exp = "/^[A-Za-z .'-]+$/";
//email field
$email_exp = '/^[A-Za-z0-9._%-]+#[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/';
//validate name field
if($name == ""){
$name_error="* Please enter your name";
$correct = false;
}
else if (!preg_match($string_exp,$name)) {
$name_error= "* Wrong Format";
$correct= false;
}
//validate surname
if($surname == ""){
$surname_error= "* Please enter your surname.";
$correct= false;
}
else if(!preg_match($string_exp,$surname)){
$surname_error= "* Wrong Format";
$correct = false;
}
//check email
if($email==""){
$email_error="* Please enter your email";
$correct = false;
}
else if(!preg_match($email_exp,$email)){
$email_error = "* Wrong Format";
$correct = false;
}
//check number
if($number=""){
$phone_error = "* Please enter your phone number";
$correct = false;
}
else if(!is_numeric($number)){
$phone_error ='* Please enter only numbers 0-9.';
$correct = false;
}
//proceed if all fields validate
if($correct){
$email_to = "tim#yah.co";
$subject ="New Enquiry";
//set message
$email_message .= "First Name: ".($name)."\n";
$email_message .= "Last Name: ".($lastname)."\n";
$email_message .= "Email: ".($email)."\n";
$email_message .= "Telephone: ".($telephone)."\n";
$email_message .= "Model: ".($model)."\n";
// create email headers
$headers = 'From: '.$email."\r\n".
'Reply-To: '.$email."\r\n" .
#mail($email, $email_subject, $email_message, $headers);
header("thankyou.php");
exit();
}//end if
}// end isset
if anyone could point me in the right direction it would be greatly appreciated.
You have to use javascript in order to validate the inputs of the form.
If you want to use PHP validation, then an AJAX request should be made.
See the following example using jquery:
$('#enquire').submit(function(e){
e.preventDefault()
var $form = $(this);
$.post(
$form.attr('action'),
$form.serialize(),
function(data) {
if (data.isError) {
// do something with the error messages or other parameter
console.log(data.errorMessages);
} else {
// make redirection
document.location.href = "thankyou.php"
}
},
'json'
);
});
in your PHP code you must output data like this:
$errorMessages = array();
if($name == ""){
$errorMessages[] = "* Please enter your name";
}
else if (!preg_match($string_exp,$name)) {
$errorMessages[] = "* Wrong Format";
}
//validate surname
if($surname == ""){
$errorMessages[] = "* Please enter your surname.";
}
else if(!preg_match($string_exp,$surname)){
$errorMessages[] = "* Wrong Format";
}
// after all validations return the results or continue registering the user
if (!empty($errorMessages)) {
die(json_encode(array('isError' => true, 'errorMessages' => $errorMessages)));
}
// continue here the registration
This is not a php issue. PHP is a server-side scripting tool which inherently means you need to send data to a server for PHP to be of use.
As mentioned by others you're most likely to be best served with a JavaSript Library
A very common and useful one is J-Query Validate but , to be sure, there are many others.
To validate the data in the form without submitting it, you will have to use javascript.
Here is a sample:
<form id="enquire" method="post" action="thankyou.php">
<div id='error-box' style='color:red;display:none'></div>
<h2>Test Drive an Audi Today</h2>
<input type="text" value="Name" class="textbox" id="name" name="name" onfocus="if(this.value=='Name') this.value='';" /><br />
<br />
<input type="text" value="Surname" class="textbox" id="surname" name="surname" onfocus="if(this.value=='Surname') this.value='';" /><br />
<br />
<input type="text" value="Contact Number" class="textbox" id="nr" name="nr" onfocus="if(this.value=='Contact Number') this.value='';" /> <br />
<br />
<input type="text" value="Email" class="textbox" id="email" name="email"onfocus="if(this.value=='Email') this.value='';" /><br />
<br />
<select id="swapImg" name="model" class="modelSelect" onchange="swapImage()" >
<option value="images/1.jpg">A4</option>
<option value="images/2.jpg" selected="selected">A6</option>
<option value="images/3.jpg">A8</option>
</select>
<br />
<br />
<input type="submit" name="submit" class="butt" value="Send" />
<span class="buttonText">We'll Call you Back!</span>
</form>
<script type='text/javascript'>
var name=document.getElementById('name');
if (name.value == null || name.value==""){
errors['no_name']="Please enter your name";
}
//Repeat something similar for each field
//Display all errors on the same page in the error box
error_box=document.getElementById('error-box');
for(error in errors){
error_box.innerHTML=error.value + "<br/>";
}
</script>
Javascript would be the best way to accomplish this, however it is possible to do it without it. In order to accomplish it, you would have to use a self-targeting form rather than an outside script. This means the action attribute of the form is the script it self. Here is an example of the basic layout for the self targeting form:
<?php
if(isset($_POST)){
$correct = true;
//ENTER VERIFICATION CODE HERE. IF AN ELEMENT VERIFIES, LEAVE IT BE. IF AN ELEMENT DOES NOT VERIFY, CHANGE THE POST VALUE TO THE ERROR MESSAGE.
if($_POST['number']=""){
$_POST['number'] = "* Please enter your phone number";
$correct = false;
}else if(!is_numeric($_POST['number'])){
$_POST['number'] ='* Please enter only numbers 0-9.';
$correct = false;
}
//AND SO ON FOR ALL INPUT ELEMENTS
if($correct){
//SEND EMAIL CODE HERE
}else{
//DISPLAY FORM WITH POST VARIABLES AS THE VALUE ATTRIBUTE
echo "<input type='text' name='number' value='" . $_POST['number'] . "'>";
//AND SO ON FOR ALL FORM ELEMENTS
}
}else{
//DISPLAY FORM AS USUAL
}
Recap of code: If $_POST is set, verify the data. If an element does not verify change the invalid $_POST value to the error message, then use those $_POST values to build the next form. If all elements verify, then send the email. If $_POST is not set, then display the form as usual because we know that the user has not entered any data yet. Good Luck!
You must use javascript to validate on browser side.
You can use pure javascript or a jquery plugin:
Javascript
function validateForm()
{
var x=document.forms["myForm"]["fname"].value;
if (x==null || x=="")
{
alert("First name must be filled out");
return false;
}
}
Get more informations here:
http://www.w3schools.com/js/js_form_validation.asp
Using Jquery you can use this:
http://jqueryvalidation.org/files/demo/

Redirect when i submit? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
Every time i click the submit button the page re-directs.
how can i set it up so that the page does not re-direct and it runs the server side code staying on the current page and echoing above my form?
HTML Code:
<form name="contact_form" method="post" action="mail.php">
<table border="0">
<tbody class="Form">
<tr>
<td>
<label for="NameInput">Your Name:<font color="#FF0000">*</font></label>
<input autofocus="autofocus" placeholder="John Doe" id="NameInput" name="NameInput" required="required" />
</td>
</tr>
<tr>
<td>
<label for="CompanyName">Your Company:<font color="#FF0000">*</font></label>
<input required="required" placeholder="Warner bros." id="CompanyName" name="CompanyName" />
</td>
</tr>
<tr>
<td>
<label id="PhoneNumber" name="PhoneNumber">Phone: </label>
<input placeholder="888-888-8888" id="PhoneNumber" name="PhoneNumber"/>
</td>
</tr>
<tr>
<td>
<label id="Email" name="Email">Email:<font color="#FF0000">*</font></label>
<input required="required" placeholder="johndoe#gmail.com" id="Email" name="Email" type="email" />
</td>
</tr>
<tr>
<td>
<label for="Website">Website: </label>
<input placeholder="https://" id="Website" name="Website" />
</td>
</tr>
</tbody>
</table>
<br/>
<br/>
<br/>
<br/>
<p><strong>What interests you, broadly speaking?</strong></p>
<br/>
<p><input id="WebDesignCheckbox" name="WebDesignCheckbox" type="checkbox">Web Design/Development</input></p>
<input id="SocialMediaCheckbox" name="SocialMediaCheckbox" type="checkbox">Social Media</input>
>
<input id="MobilePresence" name="MobilePresence" type="checkbox">Mobile Presence</input>
<input id="OnlineAdvertising" name="OnlineAdvertising" type="checkbox">Online Advertising</input>
<input id="SEOCheckbox" name="SEOCheckbox" type="checkbox">Search Engine Optamization</input>
<p><input id="ecommerceCheckbox" name="ecommerceCheckbox" type="checkbox" >eCommerce</input></p>
<br/>
<label for="comments">Your Ideas to Life?</label><br/>
<textarea placeholder="How can we help you?" id="comments" name="comments" style="margin: 2px; height: 137px; width: 437px;"></textarea></td></tr><br/>
<tr>
<td><input type="submit" id="Submit" name="Submit" value="Submit" align="middle" /></td>
</tr>
<p id="req-field-desc"><span class="required">*</span> indicates a required field</p>
</form>
PHP Script mail.php:
<?php
if( isset($_POST) ){
//form validation vars
$formok = true;
$errors = array();
//sumbission data
$ipaddress = $_SERVER['REMOTE_ADDR'];
$date = date('d/m/Y');
$time = date('H:i:s');
//form data
$NameInput = $_POST['NameInput'];
$CompanyName = $_POST['CompanyName'];
$PhoneNumber = $_POST['PhoneNumber'];
$Email = $_POST['Email'];
$Website = $_POST['Website'];
$WebDesignCheckbox = $_POST['WebDesignCheckbox'];
$SocialMediaCheckbox = $_POST['SocialMediaCheckbox'];
$MobilePresence = $_POST['MobilePresence'];
$OnlineAdvertising = $_POST['OnlineAdvertising'];
$SEOCheckbox = $_POST['SEOCheckbox'];
$ecommerceCheckbox = $_POST['ecommerceCheckbox'];
$comments = $_POST['comments'];
//form validation
if(empty($NameInput)){
$formok - false;
$errors[] = "You have not entered a name.";
}
if(empty($CompanyName)){
$formok = false;
$errors[] = "You have not entered a company name.";
}
if(empty($Email)){
$formok = false;
$errors[] = "You have not entered an email address.";
}
//send email if checks out
if($formok){
ini_set("sendmail_from","keeano#doodleinc.co");
/*$headers="From: Contact Page: {$Email}" . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";*/
$emailbody = "
<p>Time: {$time} \n {$date}</p>
<p>You are recieving this from your websites contact form.</p>
<p><strong>Contacts Name: </strong> {$NameInput}</p>
<p><strong>Companys Name: </strong> {$CompanyName}</p>
<p><strong>Phone Number: </strong> {$PhoneNumber}</p>
<p><strong>Email: </strong> {$Email}</p>
<p><strong>Website: </strong> {$Website}</p>
<p><strong>Web Design Checkbox: </strong> {$WebDesignCheckbox}</p>
<p><strong>Social Media Checkbox: </strong> {$SocialMediaCheckbox}</p>
<p><strong>Mobile Presence: </strong> {$MobilePresence}</p>
<p><strong>Online Advertising: </strong> {$OnlineAdvertising}</p>
<p><strong>SEO Checkbox: </strong> {$SEOCheckbox}</p>
<p><strong>eCommerce Checkbox: </strong> {$ecommerceCheckbox}</p>
<p><strong>Comments: </strong> {$comments}</p>
<p><strong>Extra Data Obtained:</strong>\n Users IPAddress: {$ipaddress}</p>
";
mail("keeano#doodleinc.co", "Contacts Page Enquiry", $emailbody);
echo('<p style="font-weight: bold; color: #709900"><em>Thank you for contacting doodle Inc., someone will contact you within 48 hours.</em></p>');
}
}
I would simply like to get this to create a label at the top of the Form saying "Thank you, someone will be in touch with you within 48 hours."
If someone can help me that would be great as well as detail the explanation so i never run into this problem again.
The thing is you have mail.php as your action for the form tag.
you could just leave it blank, then the form will post to the same page (contact.php)
To get the functionality working on that page you could include your mail.php file before the form, so that the errors are displayed on that same page.
just a require("mail.php"); at the top of the code will do.
You could look at doing a javascript event on the submit button. Then use json and ajax to process your form etc, return a success/fail message, and insert into where the form was. This will not 'redirect' the user to a different page, the form will get replaced by a success message.
<form method="get" action="" onsubmit="jsquickcomp(this); return false;" > // or something like this for your form heading.
Then you js function....
function jsquicksub(po_form) {
if (gb_ajaxbusy)
return false;
gb_ajaxbusy = true;
var lo_request = {};
lo_request.n = $(po_form).find('#sub-firstname').val();
lo_request.e = $(po_form).find('#sub-email').val();
// etc etc
$(po_form).fadeTo(200, 0.3);
$.getJSON('/mail.php', lo_request, function(po_result) { // this is your mail.php which performs all the php side of the form stuff
gb_ajaxbusy = false;
$(po_form).fadeTo(0, 1);
if (!po_result.success) {
alert(po_result.content); // has an alert box for error message. Can change it for anything
return false;
}else{
setTimeout(function() {
$.modal.close();
}, 2500);
}
$(po_form).replaceWith(po_result.content); // replaces the form with the success message
});
}
Then in your mail.php
// function gets passed values after validation and returns a message to the user on screen
function jsonreturn($pb_success, $ps_content = null) {
$lo_result = (object) array('success'=>$pb_success, 'content'=>$ps_content);
ob_clean();
echo json_encode($lo_result);
exit;
} // end jsonreturn()
// use $_GET to get all the values you have send through from your js file
// validate the data and do whatever you want to do with it
// these return the message that will replace the form
jsonreturn(true, 'Success!'); // for success
jsonreturn(false, 'Fail'); // for fail
Hope that makes some sense?

Form checkboxes to PHP email - code not working so far

I have a basic form, with checkboxes, that on submission is to email to the administrator (and a copy to the client).
The code I have echoes only the last checkbox (which therefore only displays one checkbox on the emails) - I can't get it to send all of the checkbox information in the email (even after trying several versions of code from on here).
<form method="POST" name="contactform" action="include/contactstationcode.php">
<h1>Quick Contact Form</h1>
<p>
<section id="nameLabel" class="labelClass"><label id="Name">Full Name: </label><input name="name" id="name" size="30" class="inputField" type="text"><br></section>
<section id="nameLabel" class="labelClass"><label id="Student ID">Student ID: </label><input name="studentid" id="studentid" size="8" class="inputField" type="text"><br></section>
<section id="nameLabel" class="labelClass"><label id="Email">Email: </label><input name="email" id="email" size="30" class="inputField" type="text"><br></section>
<section id="nameLabel" class="labelClass"><label id="ContactNumber">Contact Number: </label><input name="contactnumber" id="contactnumber" size="30" class="inputField" type="text"><br></section>
<section id="nameLabel" class="labelClass"><label id="interests">Interests: <input type="checkbox" name="check_list[]" value="Presenting " checked> Presenting<br><input type="checkbox" name="check_list[]" value="Producing "> Producing<br><input type="checkbox" name="check_list[]" value="Audio Production ">Audio Production<br><input type="checkbox" name="check_list[]" value="Marketing "> Marketing<br><br><input type="checkbox" name="check_list[]" value="Web "> Web<br>
<section id="messageLabel" class="labelClass"><label>Relevant Experience:</label></section>
<section id="messageInput" class="inputClass"><textarea name="experience" id="experience" cols="30" rows="3"></textarea><br></section><br>
<section id="buttonClass" class="buttonClass"><input src="images/submit.png" onmouseover="this.src='images/submit2.png'" onmouseout="this.src='images/submit.png'" alt="submit" value="submit" height="25" type="image" width="70"></section>
</p>
</form>
The PHP Script that I have is:
<?php date_default_timezone_set('Europe/London');
$from = 'From: company#company.com';
$today = date('l, F jS Y.');
$to = 'secret#secret.com';
//Form Fields
$name = $_POST['name'];
$studentid = $_POST['studentid'];
$email = $_POST['email'];
$contactnumber = $_POST['contactnumber'];
$experience = $_POST['experience'];
if(!empty($_POST['check_list'])) {
foreach($_POST['check_list'] as $check) {
$check=$check.',';
}
}
//Admin Email Body
$subject = 'ClickTeesside.com Get Involved Request';
$bodyp1 = "You have received a Get Involved Request through the ClickTeesside website on $today \n\nFrom: $name ($studentid)\nEmail Address: $email\nContact Number: $contactnumber";
$bodyp2 = "\n\nInterests include: ".$check;
$bodyp3 = "\n\nPrevious Experience: $experience";
$bodyp4 = "\n\nIf suitable, please get in touch with this candidate as soon as possible - the candidate has also received an automated response.";
$body=$bodyp1.$bodyp2.$bodyp3.$bodyp4;
mail ($to, $subject, $body, $from);
//Candidate Email
$candidatesubject = 'ClickTeesside.com Get Involved: Automated Email';
$candidatefrom = 'From: ClickTeesside.com';
$cbody = "Thank you for emailing Click Radio about becoming involved with the station.\nWe've sent your details to our Station Management, who will review your application.\nIf successful, we will contact you in due course.\n\n";
$cbody2 = "Here is a copy of what you sent to us on $today:\n\nName: $name ($studentid)\nEmail Address: $email\nContact Number: $contactnumber\nSpecified Interested Areas: ".$check."\n\nPrevious Experience: $experience";
$candidatebody = $cbody.$cbody2;
mail ($email, $candidatesubject, $candidatebody, $from);
header("Location: http://www.google.co.uk/");
?>
Can't see where i am going wrong - so if you could point me in the right direction :)
Thanks!
The problem is here:
foreach($_POST['check_list'] as $check) {
$check=$check.',';
}
$check is set to the value of the current item on each iteration of the loop. On the last loop, $check will be set to the last item and then you will append ,.
To resolve the issue, use a different variable name in the loop:
$check = "";
foreach($_POST['check_list'] as $c) {
$check .= $c.',';
}
The above preserves more of your code and better illustrates the problem, but the way to do this is with the implode function.
$check = implode(",", $_POST['check_list']);
This will give you the same string without a trailing comma.
Edit this:
if(!empty($_POST['check_list'])) {
foreach($_POST['check_list'] as $check) {
$check=$check.',';
}
}
with this:
$allChecks = '';
if(!empty($_POST['check_list'])) {
foreach($_POST['check_list'] as $check) {
$allChecks .= $check.',';
}
}
then send $allChecks by mail:
$bodyp2 = "\n\nInterests include: ".$allChecks;
What you are doing in your foreach is replacing the value each time. use .= to pre pend the next value to your string.
Some other tweaks would be to check all fields are present in both PHP and client side. I tend to use the same file if im writing pure PHP, so an if(isset($_POST)): so the form action is referencing itself.
Good luck.

cant figure out php contact form verification woes

Hi I got a contact from script the internet that I have been messing around with, only problem is that the verification that I am trying to add to it just doesn't work. Basically in the form it has name, email, number, type and comment. My main verification woes are with the number field I would like it so that if it is empty it echos "no number" and when the person type in letters instead of numbers it will echo "you need to type with numbers". Something like lol. but I’m stuck. Can any of you geniuses help me? Thanks in advance here is the full code below. p.s. sorry about previous post i accidently cut off the script:$
<?php
$nowDay=date("d.m.Y");
$nowTime=date("H:i:s");
$subject = "E-mail from my site!";
if (isset($_POST['submit'])) {
//contactname
if (trim($_POST['name'] == '')) {
$hasError = true;
} else {
$name = htmlspecialchars(trim($_POST['name']));
}
//emailaddress
if (trim($_POST['email'] == '')) {
$hasError = true;
} else if (!preg_match("/^[[:alnum:]][a-z0-9_.-]*#[a-z0-9.-]+\.[a-z]{2,4}$/i",trim($_POST['name']))) {
$hasError = true;
} else {
$email = htmlspecialchars(trim($_POST['email']));
}
//phonenumber
if (trim($_POST['number'] == ''))
{
$fake_num = true;
}
else if(!is_numeric($_POST['phonenumber']))
{
$fake_num = true;
}
else
{
$number = htmlspecialchars(trim($_POST['number']));
}
//type
$type = trim($_POST['type']);
//comment
if (trim($_POST['comment'] == '')) {
$hasError = true;
} else {
$comment = htmlspecialchars(trim($_POST['comment']));
}
if (!isset($hasError) && !isset($fake_num)) {
$emailTo = 'email#hotmail.com';
$body = " Name: $name\n\n
Email: $email\n\n
Phone number: $number\n\n
Type: $type\n\n
Comment: $comment\n\n
\n This message was sent on: $nowDay at $nowTime";
$headers = 'From: My Site <'.$emailTo.'>'."\r\n" .'Reply-To: '. $email;
mail($emailTo, $subject, $body, $headers);
$emailSent = true;
}
}
?>
<?php
if(isset($hasError))
{
echo"<p>form has error</p>";
}
?>
<?php
if(isset($fake_num))
{
echo"<p>wrong num</p>";
}
?>
<?php
if(isset($emailSent) && $emailSent == true)
{
echo "<p><strong>Email Successfully Sent!</strong></p>";
echo "<p>Thank you <strong> $name </strong> for using my contact form! Your email was successfully sent and I will be in touch with you soon.</p>";
}
?>
<div id="stylized" class="myform">
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" name="bookingform" id="bookingform">
<h1>Booking form</h1>
<label>
Name
<span class="small"></span>
</label>
<input type="text" name="name" id="name" class="required"/>
<label>
Your email:
<span class="small"></span>
</label>
<input type="text" name="email" id="email" class="required"/>
<label>
Contact Number:
<span class="small"></span>
</label>
<input type="text" name="number" id="number" class="required" />
<label>
Car required:
<span class="small"></span>
</label>
<select name="type" id="type">
<option selected="selected">Manual</option>
<option>Automatic</option>
</select>
<label>
Comment:
<span class="small"></span>
</label>
<textarea cols="" rows="" name="comment" id="comment" class="required"></textarea>
<button type="submit" name="submit">Submit</button>
</form>
</div>
For checking whether a number has been entered you can use:
if (!preg_match('/^?[0-9]{0,10}$/', $_POST['number'])) {
echo "Please enter a valid number"; //Failed to meet criteria
}
Here you can also specify the amount of numbers that would constitute your valid number with the braces {0,10}, in this case, the number can be up to 11 digits long. If you required it to be only 11 digits long, then use {11}.
If you wish to check if a number has been entered at all you can use:
if (empty($_POST['number'])) {
echo "Please enter a valid number"; //Field was left empty
}
PHP does have a built-in email validation function that you can use
filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)
which returns true if the entered email is in the correct format.

Categories