PHP contact form

I have used a free html bootstrap template, which I have then altered for my needs. It came with a standard contact form, which I have then adapeted with PHP to do all the validating and send etc. The problem I am having is that the form is not working and I don’t understand why. I have displayed below my coding. I have changed the <html> index file to <?php> I just wanted to see if anyone can something I maybe doing wrong? Thank you.

This bit of code below, is within the <head> tags

<?php
$result = '';
$errName = $errEmail = $errSubject = $errMessage = $errHuman = ''; 

if($_SERVER["REQUEST_METHOD"] == "POST") {  
$youremail = 'Test@website.co.uk';
$fromsubject = 'Your website!';
$name = $_POST['name'];
$email = $_POST['email'];
$subject = $_POST['subject']; 
$message = $_POST['message']; 
$headers = 'Website@example.co.uk';
$human = intval($_POST['human']);
	$to = $youremail; 
	$mailsubject = 'Masage recived from'.$fromsubject.
	$body = $fromsubject.
	
	'The person that contacted you is'.$name.
	 'Email:'.$mail.
	 'Subject:'.$subject.
	
	'Message:'.$message.
	
	'|---------END MESSAGE----------|'; 
	
	
		
		if (!$_POST['name']) {
			$errName = 'Please enter your name';
		}
		
		if (!$_POST['email'] || !filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
			$errEmail = 'Please enter a valid email address';
		}
		
		
		if (!$_POST['subject']) {
			$errSubject = 'Please enter your subject';
		}
		
			
		if (!$_POST['message']) {
			$errMessage = 'Please enter your message';
		}
		
		if ($human !== 5) {
			$errHuman = 'Your anti-spam is incorrect';
		}
	
	
	
if (!$errName && !$errEmail && !$errSubject && !$errMessage && !$errHuman) {	
	if (mail($headers, $to, $subject, $body));
	
	$result='<div class="alert alert-success">Thank You! I will be in touch shortly</div>';
	} else {
		$result='<div class="alert alert-danger">Sorry there was an error sending your message. Please try again later</div>';
		}
} 
?>

This is the contact form within the <body> tags

<form  method="post" class="col-md-8" action="">
            <div class="row">
                <div class="col-md-12">
                <h2>Send Enquiry</h2>
                </div>
                <div class="col-md-6">
                    <p>Your Name</p>
                    <input type="text" name="name" id="name" placeholder="First & Last Name" />
			   <?php if (isset($errName)) {
    echo '<p class="text-danger">'.$errName.'</p>';
				}?>
					
             		</div>
                <div class="col-md-6">
                    <p>Email</p>
                    <input type="text" name="email" id="email" placeholder="example@domain.com" />
					<?php if (isset($errEmail)) {
    echo '<p class="text-danger">'.$errEmail.'</p>';
					}?>
					
					
                </div>
                <div class="col-md-12">
                    <p>Subject</p>
                    <input type="text" name="subject" id="subject" placeholder="E.g. Price or service enquiry" />
					 <?php if (isset($errSubject)) {
    echo '<p class="text-danger">'.$errSubject.'</p>';
					}?>
					
          </div>
					
                </div>
                <div class="col-md-12">
                    <p>Message</p>
                    <textarea name="message" id="message"  placeholder="Write your message here..."></textarea>
					<?php if (isset($errMessage)) {
    echo '<p class="text-danger">'.$errMessage.'</p>';
					};?>
			</div>
					
			<div class="col-md-12">
                    <p>2 + 3 =</p>
                    <input type="text" name="subject" id="subject" placeholder="Your Answer" />	
				<?php if (isset($errHuman)) {
    echo '<p class="col-md-12">'.$errHuman.'</p>';
				}?>
				
			
                </div>
                <div class="col-xs-6 col-sm-3 col-md-offset-6">
                    <button type="submit">Send</button>
                </div>
                <div class="col-xs-6 col-sm-3">
                    <button type="reset">Reset</button>
                </div>
			<div id="result">
				<?php echo $result; ?>	
		</div>
            </div>
        </form>

That’s the wrong name for that field.

Oh, I didn’t notice that thank you. Could that be the reason it all doesn’t work?

Your PHP code wants to be within the <body> section.

Basically you want

if ($_SERVER["REQUEST_METHOD"] == "POST") {
  #process the submitted form
} else {
  #display the form
}

Hi, thank you. So if i put all my code above the contact form then follow your guidence?
where you have the else statement, do I just wrap the form within those brackets?

Yes, the form goes where it says #display the form. Just close and re-open the PHP tags as necessary.

Ok thank you, I will make these changes tonight and let you know how it goes. Thank you for your help so far :slight_smile:

1 Like

Hi,

I have finally got it to validate properly with your help so much appreciated. I am still having problems with it tho. It is all exactly the same as in my orignal post, minus the alteration suggested by both m_hutley and gandalf458.
For some reason, it validates and echos if wrong or right, but it doesn’t actually send an email to the address in the $youremail section (Which for here I have changed for privacy reasons).
Also, when I submit the form, the page bounces straight back to the top, where I need it to stay down the bottom, especially if incorrect data has been entered. Does anyone have an idea how i do that too please? Any help is appreciated. Thank you

Do you know that it’s not sending the email, or is it that you’re not receiving it? They’re not the same thing. Are you running this on a live server or your test environment?

There could be several reasons why an email is not being received, especially using the PHP mail() function. A more reliable way to send emails is to use something like PHPMailer or SwiftMailer.

In any event it would help to see your corrected code.

Hi Gandalf,

Thank you again for your response. Sorry I was not more percise in my explaination. I’m learning this as I go along. I have both test and live environments but for this, I have been testing it on a remote(live) server and to my own email address, to test its functionality, and I am not receiving any emails from it. My updated code below, all in the tags.

Would changing the start of the first if statement to: if(isset($_POST[‘Submit’])) , make any difference?


	  
	  		  <?php
$result = '';
$errName = $errEmail = $errSubject = $errMessage = $errHuman = ''; 

if($_SERVER["REQUEST_METHOD"] == "POST") {  
$youremail = 'this is were my email is';
$fromsubject = 'Your website!';
$name = $_POST['name'];
$email = $_POST['email'];
$subject = $_POST['subject']; 
$message = $_POST['message']; 
$headers = 'Website@testing.co.uk';
$human = intval($_POST['human']);
	$to = $youremail; 
	$mailsubject = 'Masage recived from'.$fromsubject.
	$body = $fromsubject.
	
	'The person that contacted you is'.$name.
	 'Email:'.$mail.
	 'Subject:'.$subject.
	
	'Message:'.$message.
	
	'|---------END MESSAGE----------|'; 
	
	
		
		if (!$_POST['name']) {
			$errName = 'Please enter your name';
		}
		
		if (!$_POST['email'] || !filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
			$errEmail = 'Please enter a valid email address';
		}
		
		
		if (!$_POST['subject']) {
			$errSubject = 'Please enter your subject';
		}
		
			
		if (!$_POST['message']) {
			$errMessage = 'Please enter your message';
		}
		
		if ($human !== 5) {
			$errHuman = 'Your anti-spam is incorrect';
		}
	
	
	
if (!$errName && !$errEmail && !$errSubject && !$errMessage && !$errHuman) {	
	if (mail($headers, $to, $subject, $body));
	
	$result='<div class="alert alert-success">Thank You! I will be in touch shortly</div>';
	} else {
		$result='<div class="alert alert-danger">Sorry there was an error sending your message. Please try again later</div>';
		}
} 
?> 

   <form  method="post" class="col-md-8" action="">
            <div class="row">
                <div class="col-md-12">
                <h2>Send Enquiry</h2>
                </div>
                <div class="col-md-6">
                    <p>Your Name</p>
                    <input type="text" name="name" id="name" placeholder="First & Last Name" />
			   <?php if (isset($errName)) {
    echo '<p class="text-danger">'.$errName.'</p>';
				}?>
					
             		</div>
                <div class="col-md-6">
                    <p>Email</p>
                    <input type="text" name="email" id="email" placeholder="example@domain.com" />
					<?php if (isset($errEmail)) {
    echo '<p class="text-danger">'.$errEmail.'</p>';
					}?>
					
					
                </div>
                <div class="col-md-12">
                    <p>Subject</p>
                    <input type="text" name="subject" id="subject" placeholder="E.g. Price or service enquiry" />
					 <?php if (isset($errSubject)) {
    echo '<p class="text-danger">'.$errSubject.'</p>';
					}?>
					
          </div>
					
                </div>
                <div class="col-md-12">
                    <p>Message</p>
                    <textarea name="message" id="message"  placeholder="Write your message here..."></textarea>
					<?php if (isset($errMessage)) {
    echo '<p class="text-danger">'.$errMessage.'</p>';
					};?>
			</div>
					
			<div class="col-md-12">
				<p>2 + 3 =</p>
        <input type="text" id="human" name="human" placeholder="Your Answer">
				<?php if (isset($errHuman)) {
    echo '<p class="col-md-12">'.$errHuman.'</p>';
				}?>
				
			
                </div>
                <div class="col-xs-6 col-sm-3 col-md-offset-6">
                    <button type="submit">Send</button>
                </div>
                <div class="col-xs-6 col-sm-3">
                    <button type="reset">Reset</button>
                </div>
						
			 </div>
        </form>

<div id="result">
				<?php echo $result; ?>	
		</div>
	

This line

	if (mail($headers, $to, $subject, $body));

doesn’t seem to have the parameters in the same order as the documentation suggests, unless you are using non-intuitive variable names.

I also don’t see anywhere that you specify the “from” address to send the email from. Lots of (most?) commercial mail servers require this to be present, and one that they are configured to send email from.

1 Like

Hi,

Thank you for your response. So are you saying it needs to be in order they a displayed, so like:

if (mail($subject, $headers, $to, $body));

With your second paragraph, I don’t really understand. I though the $youremail = is the email it will send the form info too, Also with the change I mentioned above(see below) would reference the form?

if(isset($_POST[‘Submit’]))

Check the manual. If you read down you’ll see where and how to specify the from address.

Gandalf,

Thank you, now what you have linked me too shows that the $to, should be first, so would it be best to take out the $to = $youremail and just put $yourmail so it is like;

if (mail($youremail, $headers, $subject, $body));

That really doesn’t make any difference - there’s no need to create $to in the first place, unless you intend to use it somewhere else and its value diverges from the value of $youremail at some point.

Carry on reading the doc, though, as there are still problems with your line of code.

But the point made by @Gandalf earlier is still valid - almost everyone who comes on here using the built-in mail() function is advised to use something else because it’s not all that reliable.

Ok I will have mess around with it. Alot of it is foreign to me at the moment and trying to make sense of it as I do it is proving difficult at the moment. Thank you for your advice.

It’s better as it is.

First of all I would like to say a big thank you for all your help you have given me, my code below is now working (as in it actual sends and I receive it). The issue I am now having is with the header. I am wanting it as a ‘from’ header, so i can specify what that it is in the from email section. How I have set it doesn’t work, and ideas please?

	  		  <?php
$result = '';
$errName = $errEmail = $errSubject = $errMessage = $errHuman = ''; 

if($_SERVER["REQUEST_METHOD"] == "POST") {  
$youremail = 'kevin@kjwtechsolutions.co.uk';
$fromsubject = 'Your website!';
$name = $_POST['name'];
$email = $_POST['email'];
$subject = $_POST['subject']; 
$message = $_POST['message']; 
$headers = 'From: Website@enterprisecontracts.co.uk';
$human = intval($_POST['human']);
	
	$body = $fromsubject.'
	
	
	The person that contacted you is: '.$name.'
		
	 Email: '.$email.'
		
	 Subject: '.$subject.'
	
	Message: '.$message.'
	
	|---------END MESSAGE----------|'; 
	
	
		
		if (!$_POST['name']) {
			$errName = 'Please enter your name';
		}
		
		if (!$_POST['email'] || !filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
			$errEmail = 'Please enter a valid email address';
		}
		
		
		if (!$_POST['subject']) {
			$errSubject = 'Please enter your subject';
		}
		
			
		if (!$_POST['message']) {
			$errMessage = 'Please enter your message';
		}
		
		if ($human !== 5) {
			$errHuman = 'Your anti-spam is incorrect';
		}
	
	
	
if (!$errName && !$errEmail && !$errSubject && !$errMessage && !$errHuman) {	
	if (mail($youremail, $subject, $headers, $body));
	
	$result='<div class="alert alert-success">Thank You! I will be in touch shortly</div>';
	} else {
		$result='<div class="alert alert-danger">Sorry there was an error sending your message. Please try again later</div>';
		}
} 
?>
if (mail($youremail, $subject, $headers, $body));

Look again at the documentation on what order the parameters need to be: http://php.net/manual/en/function.mail.php

And, I think you end that line with the wrong character to make your if() work properly.

If that doesn’t help

please expand on “doesn’t work”.

Hi,

Thank you, I needed to display the header last in the line of parameter. and I took the end ‘;’ off too. It now seems to all be working well.