Required alert on PHP contact form - php

I've been looking around for ages and haven't found an easy way of editing this code so that when the user hasn't typed anything into a required field (all of the fields are required) an alert is shown asking the user to please enter something.
Can anyone help?
<?php
$field_name = $_POST['name'];
$field_email = $_POST['email'];
$field_message = $_POST['message'];
$mail_to = 'you#yourdomain.com';
$subject = 'Site Mail';
$body_message = 'From: '.$field_name."\n";
$body_message .= 'Email: '.$field_email."\n";
$body_message .= 'Message: '.$field_message;
$headers = 'From: '.$field_email."\r\n";
$headers .= 'Reply-To: '.$field_email."\r\n";
$mail_status = mail($mail_to, $subject, $body_message, $headers);
if ($mail_status) { ?>
<script language="javascript" type="text/javascript">
alert('Thanks! Your email has been sent.');
window.location = 'index.html';
</script>
<?php
}
else { ?>
<script language="javascript" type="text/javascript">
alert('Sorry, something went wrong.');
window.location = 'index.html';
</script>
<?php
}
?>

You can use required attribute if you want to take advantage of html5 features.
Try this LINK. It shows a simple demo of how to use the required attribute.
This one too

PHP
<?php
$fields = array([0]=>$field_name,[1]=>$field_email,[2]=>$field_message);
foreach($fields as $field){
if !$field{
echo "Please enter a value.";
}
}
?>
Alternatively, you could use javascript validation, that would look something like this:
<script>
function formValid(){
var valid = true;
var fields = getElementByTag(input);
for (var i;i>=fields.length;i++){
if (!fields[i]){
getElementById('warning').style.display='inline'; // assuming the error message element is called 'warning'
getElementById('valid').value=1; // assuming we have an input that will indicate to the php code whether the form is validated
}
}
}
</script>
for this script we would then add to the beginning of the form-action php block:
if(isset($_POST['submit'])&&$_POST['valid']!=1){
// form action code goes here
}

use the code like below:-
$('.required').each(function(){
if($(this).val()=="")
{
alert("error");
}
});

The most common way to check for required fields is both on the client side (to inform the user) and the server side (to check the data is legit before we send it).
On the client side, at the point at which the form is submitted we should check to see if the fields are correct and ask the user to fix mistakes. There are a bunch of great helper libraries available to do this, a couple of the more common libraries are http://parsleyjs.org/ and http://jqueryvalidation.org/ both use jQuery and have easy examples to get started.
On the server side, as some commenters have noted, your current script is vulnerable to header injection and other nasty stuff. You might want to switch to using a library such as swiftmailer which will prevent a lot of bad stuff happening. Here is a really simple example of how to send email http://swiftmailer.org/docs/sending.html
To add server side validation to you example, as simple approach would be to check the values of $_POST['name']; before calling $mailer->send($message);

Related

Sendmail failing to send to some domains

I've got a small site set up that allows people to send a prewritten email to their representatives, by putting in their own email and their representatives email.
It's set up using sendmail, and works for sending to gmail, a personal email I have, and various other domains. However, it fails to send to the one domain that I need it to send to.
I get the following fault
<www-data#localhost.localdomain>: Sender address rejected: Domain not found
I've been looking through god knows how many things and I can't seem to figure it out seeing as it's working for everything else.
Hopefully someone can explain it. Cheers!
<?php
$field_name = $_POST['cf_name'];
$field_email = $_POST['cf_email'];
$field_recipient = $_POST['cf_recipient'];
$subject = 'Message Regarding Cuts in the Mental Health Budget';
$body_message = 'hello';
$headers = 'From: '.$field_email."\r\n";
$headers .= 'Reply-To: '.$field_email."\r\n";
$headers .= 'Return-Path: '.$field_email;
$mail_status = mail($field_recipient, $subject, $body_message, $headers);
if ($mail_status) { ?>
<script language="javascript" type="text/javascript">
alert('Thank you for the message. We hope this will get the TDs in gear.');
window.location = 'index.html';
</script>
<?php
}
else { ?>
<script language="javascript" type="text/javascript">
alert('Message failed. Please, make sure all boxes have been filled and try again.');
window.location = 'index.html';
</script>
<?php
}
?>
You have failed to set "envelope sender" email address used in MAIL FROM: command in SMTP sessions. It can be set by passing -f command line option to sendmail. See additional_parameters in mail documentation

Contact form: AJAX and jQuery animation and coding structure

I'm having this problem. Look at this: http://santz.net/index.contacto.html
Try sending whatever and see what happens (it's mine, I recieve it, send whatever no problem...). (It leaves the page, shows a dialog that says thanks for contacting us... and it redirects you to the same page). I HATE THIS!!!
I'm looking fore some AJAX and jQuery code that after the message is sent, it clears the form and opens a dialog (the common one... like the typical loggin boxes) and that fades the page and that show some "x" content...
The thing is that I don't know how to do any of this things and I'm driving crazy! If you could give me the code and tell me where to put it or just give a tutorial for noobs or something like that it would be great...
I leave here the PHP code I'm using:
<?php
$field_name = $_POST['php_name'];
$field_email = $_POST['php_email'];
$field_phone = $_POST['php_phone'];
$field_message = $_POST['php_message'];
$field_sender = 'alpha#hotmail.com';
$mail_to = 'gama#hotmail.com.ar';
$subject = 'Mensaje via Santz.net de '.$field_name;
$body_message = 'From: '.$field_name."\n";
$body_message .= 'E-mail: '.$field_email."\n";
$body_message .= 'Phone: '.$field_phone."\n";
$body_message .= 'Message: '.$field_message;
$headers = 'From: '.$field_sender."\r\n";
$headers .= 'Reply-To: '.$field_email."\r\n";
$mail_status = mail($mail_to, $subject, $body_message, $headers);
if ($mail_status) { ?>
<script language="javascript" type="text/javascript">
alert('Gracias por contactarse, en breve, me pondre en contacto.\n\nSantz Design | www.santz.net');
window.location = 'index.contacto.html';
</script>
<?php
}
else { ?>
<script language="javascript" type="text/javascript">
alert('El envio fallo. Por favor, envie un mail directamente a info#santz.net');
window.location = 'index.contacto.html';
</script>
<?php
}
?>
Try change this:
window.location.assign('http://www.santz.net/');
instead of:
window.location = 'index.contacto.html';
Showing error message on the same page, follow this example:
Add validation message in fieldset instead of js popup
And for a modal windows, use a plugin like this one:
http://www.mywebdeveloperblog.com/my-jquery-plugins/modalpoplite
Demo:
http://www.mywebdeveloperblog.com/projects/modalpoplite/demo/
saludos ;)
Why dont you use jQuery
$('input[type="submit"]').click(function(e){
e.preventDefault();
$.ajax({
type: "POST",
url: contact.php,
data: $('#contact-form"').serialize();,
success: function() {
//modal
}
});
});
something along those lines would be the ajax way of submitting your form and then pop up a window to the user saying thanks please view my form to get an idea just without popup

Stopping empty form submission PHP

I have been trying to implement server validation to prevent blank emails in my contact us page, but I am not sure on how to do it in PHP, here is my code:
<?php
$field_name = $_POST['cf_name'];
$field_email = $_POST['cf_email'];
$field_tel = $_POST['cf_tel'];
$field_message = $_POST['cf_message'];
$mail_to = 'test#test.com, test#test.com, test#test.com';
$subject = 'Just iStuff Mobile Contact Us: '.$field_name;
$body_message = 'From: '.$field_name."\n";
$body_message .= 'E-mail: '.$field_email."\n";
$body_message .= 'Telephone Number: '.$field_tel."\n";
$body_message .= 'Message: '.$field_message;
$headers = 'From: '.$field_email."\r\n";
$headers .= 'Reply-To: '.$field_email."\r\n";
$mail_status = mail($mail_to, $subject, $body_message, $headers);
if ($mail_status) { ?>
<script language="javascript" type="text/javascript">
alert('Thank you for your email, we have received your message and will reply within the next few days.');
window.location = 'contactus.html';
</script>
<?php
}
else { ?>
<script language="javascript" type="text/javascript">
alert('Message failed, please try again or email test#test.com');
window.location = 'contactus.html';
</script>
<?php
}
?>
Can anyone help me to do this, the tutorials online do not cover this way of doing it...
Thanks
Before your $mail_to..
You can validate the _POST/_GET first on server side.
<?php
if (empty($field_name) && empty($field_email) && empty($field_tel) && empty($field_message)) {
echo 'Please correct the fields';
return false;
}
?>
Alternatively, you can validate first on the client-side. It will save you time and resources.
just test the variable for "emptiness" and exit early. Something like this:
if(empty($field_email)) {
// maybe show the user a reason why this was rejected...
return;
}
You probably want to do this for just about all the input fields.
In addition, you can use JavaScript (jQuery has some nice plugins) to prevent the user from submitting invalid data in the first place. This won't remove the need to do it server side (since they can just disable JS, or someone malicious might intentionally bypass this measure), but it can make it a more user friendly experience.
You can use filter for this; since you're using the passed email address as part of the mail() operation, it's best to also validate:
$fields = filter_input_array(INPUT_POST, array(
'name' => FILTER_UNSAFE_RAW,
'email' => FILTER_VALIDATE_EMAIL,
'tel' => FILTER_UNSAFE_RAW,
'message' => FILTER_UNSAFE_RAW,
));
// check for missing fields
if (null === $fields || in_array(null, $fields, true)) {
// some or all fields missing
} elseif (in_array(false, $fields, true)) {
// some or all fields failed validation
} else {
// all fields passed validation
// use $fields['email'] as the email address
}
I've used FILTER_UNSAFE_RAW for all fields except email, but perhaps there are better filters that apply.
Try to put a submit input <input type="submit" name="sub" value="Submited"> inside your form
when it's clicked.
<?php
if (isset($_POST['sub']) {
$field_name = $_POST['cf_name'];
$field_email = $_POST['cf_email'];
$field_tel = $_POST['cf_tel'];
$field_message = $_POST['cf_message'];
if (empty($field_name) && ....)
{
exit('Field name is empty');
}
.....

Javascript, HP reload after alert wihout URL

I have an html form within a flash site. The form is php processed. Help me fix the php file so that after processing the form, the php returns the user to the flash page and reloads the html form. I tried a window.location in the php to send to the page but that did not work. It results in a white rectangle within the html code area (maybe frame but I'm not sure). How can I get just that html form reloaded? I do not want to load the entire page using a URL because that is too slow and I cannot replicate the flash state. BTW, below is a stripped down version of the code to simplify.
URL:
http://www.wix.com/efficertain/efficertainaccounting/accounting
Form Code:
Name
Phone
Best time to call
PHP Code:
$mail_to = 'info#efficertain.ca';
$subject = 'Message from a site visitor '.$field_name;
$body_message = 'From: '.$field_name."\n";
$body_message .= 'E-mail: '.$field_phone."\n";
$body_message .= 'Message: '.$field_when;
$headers = 'From: '.$field_email."\r\n";
$headers .= 'Reply-To: '.$field_email."\r\n";
$mail_status = mail($mail_to, $subject, $body_message, $headers);
if ($mail_status) { ?>
<script language="javascript" type="text/javascript">
alert('Thank you for the message. We will contact you shortly.');
window.location = 'http://www.wix.com/efficertain/efficertainaccounting/accounting';
</script>
<?php
}
else { ?>
<script language="javascript" type="text/javascript">
alert('Message failed. Please, send an email to info#efficertain.ca');
window.location = 'http://www.wix.com/efficertain/efficertainaccounting/accounting';
</script>
<?php
}
?>
You should not use window.location here as it will reload the whole browser window. Try to use document.location and you will need to pass it the URL of your form instead of the URL for the whole page as you only want to reload the iframe content. So your URL would be http://www.flashquix.com/embeds/fb4c83282b9342aa83952e74ad33dfdd?wrap=no&gzip=true&bg=transparent according to the example above.
document.location = 'http://www.flashquix.com/embeds/fb4c83282b9342aa83952e74ad33dfdd?wrap=no&gzip=true&bg=transparent';
You are already putting new content on the page.. just follow the logic and make that content your form.
else { ?>
<script language="javascript" type="text/javascript">
alert('Message failed. Please, send an email to info#efficertain.ca');
</script>
// INSERT YOUR FORM HTML HERE AND YOU'RE GOOD TO GO

Why does this validation error occur before data is submitted in PHP form?

I'm using a PHP form to forward data to an email address. Everything seems to work fine except the the error message ["You have not entered an email"] appears when the page is loaded, before any input from the user is entered, rather than through validation when submitted.
The form is here http://www.soulwatt.com/contact.php
Note: I found this PHP code online after doing a search on how to forward data to email, so it is not mine. Please excuse the lack of proper code formatting.
<?php
$to = $_REQUEST['sendto'] ;
$from = $_REQUEST['Email'] ;
$name = $_REQUEST['Name'] ;
$headers = "From: $from";
$subject = "soulwatt.com Contact Data!!";
$fields = array();
$fields{"Name"} = "Name";
$fields{"Company"} = "Company";
$fields{"Email"} = "Email";
$fields{"Phone"} = "Phone";
$fields{"list"} = "Mailing List";
$fields{"Comments"} = "Comments";
$body = "Soul Watt has received the following information:\n\n";
foreach($fields as $a => $b) {
$body .= sprintf("%20s: %s\n",$b,$_REQUEST[$a]);
}
$headers2 = "From: noreply#soulwatt.com";
$subject2 = "Thank you for contacting Soul Watt!";
$autoreply = "Thank you for contacting us. Somebody will get back to you as soon as possible, usualy within 48 hours. If you have any more questions, please consult our website at www.soulwatt.com";
if($from == '') {
print "You have not entered an email. Please enter your email and try again.";
}
else {
if($name == '') {
print "You have not entered a name.<br />Please enter your name and try again.";
}
else {
$send = mail($to, $subject, $body, $headers);
$send2 = mail($from, $subject2, $autoreply, $headers2);
if($send) {
print "<p><span>THANK YOU FOR CONTACTING US!</span></p>";
print "<p><span>Someone will get back to you as soon as possible, usually within 48 hours. If you need immediate assistance regarding booking Soul Watt, please call Randy at (828) 729-3199.</span></p>";
}
else {
print "<p><span>We encountered an error sending your mail, please notify webmaster#soulwatt.com</span></p>";
}
}
}?>
Thanks for your help!
These 2 lines:
$from = $_REQUEST['Email'] ;
if($from == '') {
print "You have not entered an email. Please enter your email and try again.";
}
Mean that you check the email request (POST and GET) key. The first time you load this page this WILL be empty. You could add a check if there was a POST at all, for instance if there was submitted.
To be honest, there might a lot of problems with your code: a user can add all sorts of stuff in there, probably even add stuff in the headers to add 'to' fields and all.. You might be making a spam-machine here. This part: $headers = "From: $from"; just adds the request field FROM in your headers....
You'd want to wrap your validation section in
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
... do validation here ...
}
... print form here ...
That will only run the validation code AFTER you submit the form. As it stands now, it's running each time the page is loaded, so of course there's no form data to validate the first time around.
Does your form fields have the same name that you're checking?
I mean for
$from = $_REQUEST['Email'];
You should have
<input type='text' name='Email' /> <!-- Note the Capital E -->
I add my comments here:
Use $_POST or $_GET. Avoid $_REQUEST. That way you've more controll over your app.
Also, don't check emptiness with =="" try empty($from)
OK So if the form is on http://www.soulwatt.com/contact.php and you have
<form method="post" action="contact.php" name="contact_form" id="contact_form">
action="contact.php" : That means it is proccessing the form on the same address so you will see the results of the form processing on the same page, and since the form is empty, and you're checking it regardless of it having been posted or not, you get that error

Categories