Invalid contact form

I was working on contactus.php form. Just to inform first that i ensuring if my form is working with the validation implemented in my code. I am not testing whether the email will be sent to our account. However, my objective is when the form is invalid, it will reload the page and redirect user back to the same page while if the form is valid, it will redirect user to contactthanks.php

However, my reload and redirect when the form is invalid wasn’t what i want it to be. I added

print "<meta http-equiv=\"refresh\" content=\"0;URL=contactus.php\">";

What is it that I am missing in the code?


    <form name="contactForm" method="post" id="contactForm"
    				onsubmit="return chkContact(this)">
    				<div class='input1'>
    					<div class="help">
    						<input id="name" name="name" type="text" placeholder="Name "
    							value="<?php echo $user_profile["name"]; ?>">
    					<div id="email-label" class="help">
    						<input id="email" name="email" type="text"
    							placeholder="Email Address " class="input-xlarge"
    							value="<?php echo $user_profile["name"]; ?>">
    					<div id="subj-label" class="help">
    						<input id="subject" name="subject" type="text"
    							placeholder="Subject " class="input-xlarge"
    							value="<?php echo $user_profile["subject"]; ?>">
    					<div id="message" class="help">
    						<textarea id="message" name="message" rows="13" cols="33"
    							placeholder="Message " class="input-xlarge"></textarea>
    					<button id="btnSubmit" type="submit" value="Send"
    						onclick="return chkContact()">Send</button>
    					<div id="msgSubmit" class="h3 text-center hidden"></div>
function chkContact(form) {
	if( == "" && == "" && form.subject.value == "" && form.message.value == "" ) {
		  alert("Please fill in the required fields: \n\u26AC Name \n\u26AC Email \n\u26AC Subject \n\u26AC Message");;
		     return false;
	 if( == "") {
	     alert("Error: Name cannot be blank!");;
	     return false;
	 if( == "") {
	     alert("Error: Email Address cannot be blank!");;
	     return false;
	   re = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
	   if(!re.test( {
	     alert("Error: Invalid email address!");;
	     return false;
	   if(form.subject.value == "") {
		     alert("Error: Subject cannot be blank!");
		     return false;
	   if(form.message.value == "") {
		     alert("Error: Message cannot be blank!");
		     return false;
	var name = document.getElementById('name').value;
	var email = document.getElementById('email').value;
	var subject = document.getElementById('subject').value;
	var message = document.getElementById('message').value;
	var dataString='name='+ name+'&email='+email+'&subject='+subject+'&message='+message;

		url: "<?php echo $base_url; ?>ajax-helper/post-email.php",
		success: function(data){
		if (/^\s*SUCCESS\s*$/.test(data)) {
		window.location = '<?php echo $base_url; ?>index?success=true';
		return false;


// session_start ();
include_once ('functions.php');
include ('php-header.php');

$EmailTo = "";
$Subject = "New Message Received";

$name = Trim ( stripslashes ( $_POST ['name'] ) );
$email = Trim ( stripslashes ( $_POST ['email'] ) );
$subject = Trim ( stripslashes ( $_POST ['subject'] ) );
$message = Trim ( stripslashes ( $_POST ['message'] ) );

// prepare email body text
$Body = "<br>";
$Body .= "Name: ";
$Body .= $name;
$Body .= "\n<br>";
$Body .= "Email: ";
$Body .= $email;
$Body .= "\n<br>";
$Body .= "Subject: ";
$Body .= $subject;
$Body .= "\n<br>";
$Body .= "Message: ";
$Body .= $message;
$Body .= "\n<br>";

// send email
$url = '..';
$fields = array (
'BASE_URL' => $base_url,
'SENDER_EMAIL' => $email,
'RECEIVER_NAME' => '..',
'SENDER_NAME' => $name,
'SUBJECT' => $subject,
'CONTENT' => $Body

$success = mail ( $EmailTo, $Subject, $Body, "From: <$email>" );

// $success = mail ( $EmailTo, $Subject, $Body, "From:" . $email );
$fields_string = json_encode ( $fields );
$ch = curl_init ();
curl_setopt ( $ch, CURLOPT_CUSTOMREQUEST, "POST" );

curl_setopt ( $ch, CURLOPT_SSL_VERIFYHOST, false );
curl_setopt ( $ch, CURLOPT_SSL_VERIFYPEER, false );

curl_setopt ( $ch, CURLOPT_URL, $url );
curl_setopt ( $ch, CURLOPT_POST, count ( $fields ) );
curl_setopt ( $ch, CURLOPT_POSTFIELDS, $fields_string );
curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, 1 );
curl_setopt ( $ch, CURLOPT_HTTPHEADER, array (
'Content-Type: application/json',
'Content-Length: ' . strlen ( $fields_string )
) );
$result = curl_exec ( $ch );
curl_close ( $ch );

if ($success) {
	echo "Message sent";
	print "<meta http-equiv=\"refresh\" content=\"0;URL=contactthanks.php\">";
} else {
	echo "Message not sent! Try again.";
	print "<meta http-equiv=\"refresh\" content=\"0;URL=contactus.php\">";


include ('includes/header.php');
include ('includes/header-search.php');
include ('includes/header-nav.php');
include ('includes/header-info.php');

<!DOCTYPE html>
<html lang="en">
<body id="contactus">
	<div class="container">
		<div class="row">
			<div class="one-half column"
				style="background-image: url(images/abtus.png); background-repeat: none;">
				<div class="txt-header" style="margin: 40px 40px;">
					<div class="about_heading">Contact Us</div>
					<div class="about_heading-txt">Send us a Message</div>

		<div class="row">
			<div class="eleven columns" style="padding-bottom: 5%;">
				<div class="google-maps">
					<iframe width="640" height="450" frameborder="0" style="border: 0"
						allowfullscreen> </iframe>
			<div class="six columns">
				<h3>Your message has been sent!</h3>
					<a href="contactus.php" style="float: right; margin: 5%;">&#9668;
						Back to Contact Form</a>
include ('includes/footer.php');

I don’t understand why you have the print statement or where it goes. Have you tried putting an action= on the form itself?

Rather than printing the meta refresh redirect, could you use a header redirect?

header('location: contactus.php');

If i used header redirect as you mentioned above, it didn’t show whether the form is valid or invalid as when I clicked on the ‘SEND’ button, it goes nowhere.

Another thing, i unsure why my form keeps giving invalid message. What went wrong in my code? it’ll be great if you could spot and informed me so that I know what went wrong.

Yes i just did. Didn’t noticed that i miss that out.

<form name="contactForm" method="post" id="contactForm" action="contactthanks.php"
					onsubmit="return chkContact(this)">

I not sure why is it that my form keep aying it’s invalid each time i tried to test it. What went wrong in my codes? It’ll be great if you could identify it as i unsure why.

Exactly what message is it giving you? I see several places where you check errors, but which test is failing? If it’s failing to send the email, is it because you’re sending it with a from-address that your server might not be configured to allow?

The message that I get is “Message was not send! Try again.” Probably it’s due to that. Forgive me for the lack of knowledge on this as it is my first time trying to create a working contact form. So meaning the email address will need to be configured in the server then my contact form can be send?

A lot of email servers will only allow emails to be sent from a domain that they are configured to send - to do otherwise means that you could be sending all sorts of spam emails with any old “from” address. Because you try to use the email address that whoever filled in the form gave, that means you’re trying to send an email from their address, but using your server. Many things might stop that, so it’s better to use your own email address as the ‘from’ address.

Also it’s a bit confusing that you use $Subject and $subject in the same php code - php allows it, as variable names are case-sensitive, but it doesn’t make it easy to figure out the difference.

Thank you very much for the explanation on the email address. it's better to use your own email address as the 'from' address. Does that means my $EmailTo under postemail.php i should use my own email? Or i should declare an $EmailFrom ? This is because some online source i saw they do not have $EmailFrom.

Also it’s a bit confusing that you use $Subject and $subject in the same php code - php allows it, as variable names are case-sensitive, but it doesn’t make it easy to figure out the difference.

I knew one of the reason is due to this. Hence, i am working on it, to change the name of $subject to something else.

The key thing is that many servers will only allow a “from” address to be one that they are configured to send from. So you either need a $emailFrom variable, or at a push you could hard code while you see if that’s the problem. It might be something else.

1 Like

It is one of my “pet peeves” that so many form scripts use what I consider to be a “contact” email address as the “from” when in reality the email is is not from them at all It is from the form!

Also, the code for the Trim function isn’t shown (typo or custom?) but I suspect that stripslashes is inadequate protection against email header injection

Yes, it’s a lazy way of doing it, just makes it easier for whoever receives these email contacts to respond just by hitting “reply”. The “reply-to” field is probably more appropriate, but isn’t supported by some email clients, or wasn’t at least.

To be honest, i still don’t get it. Do you have an example to that? Maybe it’s easier for me to interpret with the explanation you gave here.

I don’t have any full examples, but to try to narrow down whether it’s causing your problem, you could try changing this line:

$success = mail ( $EmailTo, $Subject, $Body, "From: <$email>" );

to something like this

$success = mail ( $EmailTo, $Subject, $Body, "From:" );

where in the above you would change “” to a valid working configured address on your mail server. It doesn’t matter what you want it to end up as, and whether you want to have a separate one to clearly show emails that have come from your form (which is a good idea IMO), just for now you want to see if this is the problem. If it still doesn’t send once you’re sending from a known good email address, it must be something else.

1 Like

But i still doubt it is due to the mail functionality or even due to the email not configured. This is because I tried to command out $EmailTo , $Subject and $success , the form is still showing message not send. So i’ve the feeling it is the form that got error. But i can’t see the error. Because right now i’m testing the contactus form only. Like normal form it will proceed to next page when there’s no error. i not sure if i make sense. It’s confusing.

A PITA but you may need to var_dump() exit at the breakpoints.


where should i add this in?

lol an American thing I guess, PITA = Pain In The A__

At the “breakpoints” i.e. the points in your code logic path where you want to test what variable values are before they get used. eg.

$some_array = array("something"); 
foreach ($some_array as $some_value) {

The idea is you can make sure $something is what you think it should be at various points in the code.
Then the exit stops the script so the page won’t change to another.

In the code you posted above, the error “Message not sent. Try again” is displayed if the check for $success returns false. $success is the return from the mail() function, so if the mail function fails, or you comment out the call to the mail() function, $success will be false and you will get your error message. If you want to test without the mail functionality being set up, you need to find a different way to check whether to go on to the “thanks” page.

yes I was figuring it out of another way. And i manage to check that the message was undefined. Probably it’s due to that. But still trying to solve it.