Hi there I have edited some code I have found on-line and everything works besides the validation. It always seems to send an email even when all fields are blank on the contact form that I've created. It is definitely an easy fix but I'm new to this so any help means a great deal to me!!
Thanks.
Heres the code Im using for the php script:
/////////////////////////////////////////////////////
<?php
// Contact subject
$subject ="$Email Enquiry";
// Details
$message=("$cComment") ;
// Mail of sender
$mail_from="$cEmail";
// From
$header="from: $cName <$mail_from>";
// Enter your email address
$to ='info#blahblahblah.net';
$send_contact=mail($to,$subject,$message, $header);
// Check, if message sent to your email
// display message "We've recived your information"
if($mail_from != "Email"){
header('Location:thanksemail.php');
}
else {
header('Location:emailfail.php');
}
?>
You need to check if the variables are empty before sending the email. You can do this like so:
if(!empty($variable) and
!empty($variable2)) {
// send the email out here
}
I am using the empty() function here to detect if the values are empty or not. The following values are considered to be empty values:
"" (an empty string)
0 (0 as an integer)
0.0 (0 as a float)
"0" (0 as a string)
NULL
FALSE
array() (an empty array)
var $var; (a variable declared, but without a value in a class)
I would also avoid using the standard PHP mail function and instead use a library such as PHPMailer or SwiftMailer to send out your emails instead. They give you more flexibility and both have a much nicer API to work with.
You haven't got any checking code. The code that sends the mail is $send_contact=mail($to,$subject,$message, $header);
The checking must be before this code
Try this
if($subject!="" && $cComment!="" && $cEmail!="" && $cName!="" && $mail_from!=""){
$send_contact=mail($to,$subject,$message, $header);
if($mail_from != "Email"){
header('Location:thanksemail.php');
}
else {
header('Location:emailfail.php');
}
}else{
header('Location:emailfail.php');
}
Just as a side note, you can save yourself a line or two of code by verifying if the e-mail was sent like:
if(mail($to,$subject,$message, $header)){
header('Location:thanksemail.php');
}else {
header('Location:emailfail.php');
}
If it comes back true, it was sent. If false, it was not sent.
You have put the mail() function outside your if() statement.
Just move it (and complete your if with the other fields):
<?php
if(!empty($mail_from) && !empty($Email)) {
mail($to, $subject, $message, $header);
header('Location:thanksemail.php');
} else {
header('Location:emailfail.php');
}
Related
I have this php code
if(filter_var($_POST['username'], FILTER_SANITIZE_EMAIL) !== false && filter_var($_POST['username'], FILTER_VALIDATE_EMAIL) !== false) {
echo 'it is mail';
}else{
echo 'is is phone';
}
when I'm sending the post data like this
example#bla.com
it is writing it is mail. but when I'm sending the data like this
+995216846121
then it is writing also that it is mail
what is wrong?
please help me.
I need to check if client add mail or phone number.
I added one more check with is_numeric() and now everithing is good.
thenk you All!!!
I am using a form to get newsletter sign ups on my website. I am using a contact.php file which works well but there is no validation so I occasionaly and sometimes frequently get blank responses.
I'm not sure why this is, but I believe I need validation.
This is my original code
<?php
/*
Author: Andrew Walsh
Date: 30/05/2006
Codewalkers_Username: Andrew
This script is a basic contact form which uses AJAX to pass the information to php, thus making the page appear to work without any refreshing or page loading time.
*/
$to = "hello#interzonestudio.com"; //This is the email address you want to send the email to
$subject_prefix = ""; //Use this if you want to have a prefix before the subject
if(!isset($_GET['action']))
{
die("You must not access this page directly!"); //Just to stop people from visiting contact.php normally
}
/* Now lets trim up the input before sending it */
$subject = "Newsletter Sign Up"; //The senders subject
$message = trim($_GET['email']); //The senders subject
$email = trim($_GET['email']); //The senders email address
mail($to,$subject,$message,"From: ".$email.""); //a very simple send
echo 'contactarea|Thank you. We promise you won’t regret it.'; //now lets update the "contactarea" div on the contact.html page. The contactarea| tell's the javascript which div to update.
?>
and this is the code I tried to add to validate but it doesnt work.
<?php
/*
Author: Andrew Walsh
Date: 30/05/2006
Codewalkers_Username: Andrew
This script is a basic contact form which uses AJAX to pass the information to php, thus making the page appear to work without any refreshing or page loading time.
*/
$to = "jcash1#gmail.com"; //This is the email address you want to send the email to
$subject_prefix = ""; //Use this if you want to have a prefix before the subject
if(!isset($_GET['action']))
{
die("You must not access this page directly!"); //Just to stop people from visiting contact.php normally
}
/* Now lets trim up the input before sending it */
$subject = "Newsletter Sign Up"; //The senders subject
$message = trim($_GET['email']); //The senders subject
$email = trim($_GET['email']); //The senders email address
/* Validation */
$error=0; // check up variable
$errormsg = '<ul class="errorlist">';
/* get it checking */
if(!check_email($email))
{
$errormsg.= "<li class='errormessage'>ERROR: not a valid email.</li>";
$error++;
}
$errormsg .= '</ul>';
if($error == 0) {
mail($to,$subject,$message,"From: ".$email.""); //a very simple send
echo 'contactarea|Thank you. We promise you won’t regret it.'; //now lets update the "contactarea" div on the contact.html page. The contactarea| tell's the javascript which div to update.
} else {
echo 'error|'. $errormsg;
}
?>
Can anyone offer some insight?
I cannot for the life of me get this to work...
I am getting an Error with the plugin and I have loaded it correctly
so I tried adding this :
if (filter_var($email, FILTER_VALIDATE_EMAIL) === true) {
//your email sending code here
} else {
echo("$email is not a valid email address");
}
like so:
<?php
/*
Author: Andrew Walsh
Date: 30/05/2006
Codewalkers_Username: Andrew
This script is a basic contact form which uses AJAX to pass the information to php, thus making the page appear to work without any refreshing or page loading time.
*/
$to = "hello#interzonestudio.com"; //This is the email address you want to send the email to
$subject_prefix = ""; //Use this if you want to have a prefix before the subject
if(!isset($_GET['action']))
{
die("You must not access this page directly!"); //Just to stop people from visiting contact.php normally
}
/* Now lets trim up the input before sending it */
if (filter_var($email, FILTER_VALIDATE_EMAIL) === true) {
$subject = "Newsletter Sign Up"; //The senders subject
$message = trim($_GET['email']); //The senders subject
$email = trim($_GET['email']); //The senders email address
mail($to,$subject,$message,"From: ".$email.""); //a very simple send
echo 'contactarea|<div id="thanks">Thank you. We promise you won’t regret it.</div>'; //now lets update the "contactarea" div on the contact.html page. The contactarea| tell's the javascript which div to update.
} else {
echo("$email is not a valid email address");
}
?>
Which is not working. I think it is beauce I have implemented the code in the wrong place but I am not sure. Any help would be greatly appreciated.
You can use filter_var() function in PHP for validating email addresses.
For simply validating email addresses in PHP you can use it like this,
if(filter_var($email, FILTER_VALIDATE_EMAIL)){
echo "Valid email";
}
And your code can be improved like this.
if(filter_var($email, FILTER_VALIDATE_EMAIL)){
mail($to,$subject,$message,"From: ".$email.""); //a very simple send
echo 'contactarea|Thank you. We promise you won’t regret it.'; //now lets update the "contactarea" div on the contact.html page. The contactarea| tell's the javascript which div to update.
}
else {
$errormsg.= "<li class='errormessage'>ERROR: not a valid email.</li>";
$error++;
echo '</ul> error|'. $errormsg;
}
If you want to know more about it, visit official PHP documentation page here : http://php.net/manual/en/filter.filters.validate.php
Or use jquery validation plugin. I highly recommend it.
Code will look similar to below
$( "#myform" ).validate({
rules: {
field: {
required: true,
email: true
}
}
});
You can use server side validation by using this code
if (filter_var($email, FILTER_VALIDATE_EMAIL) === true) {
//your email sending code here
} else {
echo("$email is not a valid email address");
}
I have made a contact form based on this tutorial:
http://blog.teamtreehouse.com/create-ajax-contact-form
I'm using PHP Version 5.3.10-1ubuntu3.4 on my server and I've been having trouble with http_response_code(); which is what the example tutorial at the above link uses. I've read http_response_code(); only works with PHP 5.4. So instead I have reverted to using header();.
I have my form working just fine and it's displaying a success message when I submit, rather than errors when I was using http_response_code(); but my PHP isn't that great and I am wanting to know if what I have done is acceptable or if I should be doing it a different way? Please correct my code if so.
Here's the contents of my mailer.php file, where you can see I've commented out http_response_code(); and am using header();.
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Get the form fields and remove whitespace.
$name = strip_tags(trim($_POST["name"]));
$name = str_replace(array("\r","\n"),array(" "," "),$name);
$email = filter_var(trim($_POST["email"]), FILTER_SANITIZE_EMAIL);
$phone = trim($_POST["phone"]);
$company = trim($_POST["company"]);
$minbudget = trim($_POST["minbudget"]);
$maxbudget = trim($_POST["maxbudget"]);
$message = trim($_POST["message"]);
$deadline = trim($_POST["deadline"]);
$referred = trim($_POST["referred"]);
// Check that data was sent to the mailer.
if ( empty($name) OR empty($phone) OR empty($message) OR !filter_var($email, FILTER_VALIDATE_EMAIL)) {
// Set a 400 (bad request) response code and exit.
//http_response_code(400);
header("HTTP/1.1 400 Bad Request");
echo "Error (400). That's not good, refresh and try again otherwise please email me and let me know you are having trouble submitting this form.";
exit;
}
// Set the recipient email address.
// FIXME: Update this to your desired email address.
$recipient = "myemail#domain.com";
// Set the email subject.
$subject = "Website enquiry from $name";
// Build the email content.
$email_content = "Name: $name\n";
$email_content .= "Email: $email\n\n";
$email_content .= "Phone: $phone\n";
$email_content .= "Company: $company\n\n";
$email_content .= "Budget: $minbudget $maxbudget\n";
$email_content .= "Deadline: $deadline\n";
//$email_content .= "Max Budget: $maxbudget\n";
$email_content .= "\n$message\n\n";
$email_content .= "Referred: $referred\n";
// Build the email headers.
$email_headers = "From: $name <$email>";
// Send the email.
if (mail($recipient, $subject, $email_content, $email_headers)) {
// Set a 200 (okay) response code.
//http_response_code(200);
header("HTTP/1.1 200 OK");
echo "Thank You! I'll be in touch soon.";
} else {
// Set a 500 (internal server error) response code.
//http_response_code(500);
header("HTTP/1.0 500 Internal Server Error");
echo "Error (500). That's not good, refresh and try again otherwise please email me and let me know you are having trouble submitting this form.";
}
} else {
// Not a POST request, set a 403 (forbidden) response code.
//http_response_code(403);
header("HTTP/1.1 403 Forbidden");
echo "Error (403). That's not good, refresh and try again otherwise please email me and let me know you are having trouble submitting this form.";
}
I've managed to answer this on my own similar question by going through the PHP source code to work out exactly what happens.
The two methods are essentially functionally equivalent. http_response_code is basically a shorthand way of writing a http status header, with the added bonus that PHP will work out a suitable Reason Phrase to provide by matching your response code to one of the values in an enumeration it maintains within php-src/main/http_status_codes.h.
Note that this means your response code must match a response code that PHP knows about. You can't create your own response codes using this method, however you can using the header method. Note also that http_response_code is only available in PHP 5.4.0 and higher.
In summary - The differences between http_response_code and header for setting response codes:
Using http_response_code will cause PHP to match and apply a Reason Phrase from a list of Reason Phrases that are hard-coded into the PHP source code.
Because of point 1 above, if you use http_response_code you must set a code that PHP knows about. You can't set your own custom code, however you can set a custom code (and Reason Phrase) if you use the header function.
http_response_code is only available in PHP 5.4.0 and higher
Easy solution:
/**
* Sets the response code and reason
*
* #param int $code
* #param string $reason
*/
function setResponseCode($code, $reason = null) {
$code = intval($code);
if (version_compare(phpversion(), '5.4', '>') && is_null($reason))
http_response_code($code);
else
header(trim("HTTP/1.0 $code $reason"));
}
you can use it as:
setResponseCode(404);
or
setResponseCode(401,'Get back to the shadow');
To answer your main question, the biggest response I could see to using headers vs http_response_code(), is that http_response_code() is only supported on PHP 5.4 and greater, older versions would fail using that function.
Using headers as you are in your example will insure you're code will work on older versions.
im getting the "invalid email address"
all is hardcoded for testing, what is missing? thanks!
<html>
<head><title>PHP Mail Sender</title></head>
<body>
<?php
/* All form fields are automatically passed to the PHP script through the array $HTTP_POST_VARS. */
$email = $HTTP_POST_VARS['example#example.com'];
$subject = $HTTP_POST_VARS['subjectaaa'];
$message = $HTTP_POST_VARS['messageeeee'];
/* PHP form validation: the script checks that the Email field contains a valid email address and the Subject field isn't empty. preg_match performs a regular expression match. It's a very powerful PHP function to validate form fields and other strings - see PHP manual for details. */
if (!preg_match("/\w+([-+.]\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*/", $email)) {
echo "<h4>Invalid email address</h4>";
echo "<a href='javascript:history.back(1);'>Back</a>";
} elseif ($subject == "") {
echo "<h4>No subject</h4>";
echo "<a href='javascript:history.back(1);'>Back</a>";
}
/* Sends the mail and outputs the "Thank you" string if the mail is successfully sent, or the error string otherwise. */
elseif (mail($email,$subject,$message)) {
echo "<h4>Thank you for sending email</h4>";
} else {
echo "<h4>Can't send email to $email</h4>";
}
?>
</body>
</html>
Change
$email = $HTTP_POST_VARS['jaaanman2324#gmail.com'];
$subject = $HTTP_POST_VARS['subjectaaa'];
$message = $HTTP_POST_VARS['messageeeee'];
to
$email ='jaaanman2324#gmail.com';
$subject ='subjectaaa';
$message = 'messageeeee';
I think you want it to be hardcoded like this:
$email = 'jaaanman2324#gmail.com';
Otherwise you are trying to get the value out of HTTP_POST_VARS with the key of jaaanman2324#gmail.com
First, don't use $HTTP_POST_VARS, it's $_POST now.
Second, by writing $HTTP_POST_VARS['jaaanman2324#gmail.com'] you're looking for table element with juanman234#gmail.com key.
That's not what you wanted to do.
If you want to hardcode it, write
$email = 'jaaanman2324#gmail.com';`
if not, write
$email = $_POST['email'];
to get email field from form.
Here is the code I'm using for the submitHandler:
submitHandler: function() {
$('.holder').fadeOut('slow');
$('#loading').fadeIn('slow');
$.post('email.php',{name:$('#em_name').val(), email:$('#em_email').val(), message:$('#em_message').val()},
function(data){
$('#loading').css({display:'none'});
if( data == 'success') {
$('#callback').show().append('Message delivered successfully');
$('#emailform').slideUp('slow');
} else {
$('#callback').show().append('Sorry but your message could not be sent, try again later');
}
});
}
This isn't working when used in conjunction with this php:
<?php $name = stripcslashes($_POST['name']);
$emailAddr = stripcslashes($_POST['email']);
$message = stripcslashes($_POST['message']);
$email = "Message: $message \r \n From: $name \r \n Reply to: $emailAddr";
$to = 'mail#example.com';
$subject = 'Message from example';
//validate the email address on the server side
if(eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $emailAddr) ) {
//if successful lets send the message
mail($to, $subject, $email);
echo('success'); //return success callback
} else {
echo('An invalid email address was entered'); //email was not valid
}
?>
Does anyone have any suggestions as to why this isn't working like it should. It seems to just lock up when I submit. Any help would be appreciated. Thanks!
Recommendations
Get firebug or httpfox to debug ajax scripts. You can see all requests made and the post/get variables.
Dont use eregi use preg
Dont use preg to validate email use php's filter functions
Another debugging idea: set the $_POST vars above the email.php code and visit the email.php in your browser to see if its working.