Html5 Contact Form with Php GD library and Google Maps API

Coding \ Html-css Sunny Comments June 17th 2013
In this tutorial I'm going to show you how to create a pretty awesome 'Contact us' page. This page will contain the right amount of features that I think most Contact us pages should have. It will contain a contact form which will use Html5 for client site validation, Php for server side validation and a neat trick to avoid spammers. We will also use the Php's GD library for showing our email and phone number in the form of images, so that, again, spammers have some difficulty in harvesting them. Finally, we will use the Google Maps API to show our desired location on a zoom-able and pan-able map.

As you can imagine, this tutorial will cover a lot of topics, but you do not need a lot of knowledge of Php or JavaScript, or any knowledge of Google Maps API to use this tutorial, but some knowledge of Html and Css is required. Without further ado, let's get started!
Download Source Code

Heads up

First section of this tutorial will cover actually creating the form and sending the user's message to our email address and doing all the validation. Next we will use the Php GD library to display our email and phone number; and lastly, we will work on the Google Maps API. Below is the picture of what the final product will look like, along with the link to the demo.

screen22.png View Demo

Basic markup and style

For getting started we only need contact.php and syle.css and later we will add few other files and also modify these two files, as we go along.

contact.php
<!doctype html>
<html lang="en">
<head>
	<title>Contact us</title>
	<meta http-equiv="Content-Type" charset="UTF-8" />
	<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div id="container">
	<div id="form">

	</div>
	<div id="details">

	</div>
	<div class="clear"></div>
</div>
</body>
</html>

The div with id="container" is our main container. The div with id="form" will contain the form and the div with id="details" will contain the phone number, email and the map. Now the style.css:

style.css
body {
	font-family: Verdana, Arial, Helvetica, sans-serif;
	background-color: #bbb;
	color: #222;
	margin: 0;
	padding: 0;
}

a{
	color: blue;
}

p{
	margin-bottom: 15px;
}

#container{
	padding: 40px;
	margin: 50px auto;
	width: 940px;
	background: #fff;
}

#form{
	float: left;
	width: 499px;
	padding-right:30px;
	border-right: 1px solid #eee;
	min-height: 480px;
}

#details{
	float: left;
	width: 380px;
	min-height: 420px;
	padding-left: 30px;
}

.clear{
	clear: both;
}

Here we have simply set some basic styles for the elements in our contact.php page.

Creating the form

In this section we will create the form, do client and sever-side validation and then enable sending the user's message to our email address.

Markup and style for our form

Below is the markup for our form, with the Name, Email, and Message fields.

Inside contact.php
<h2>FOR A GENERAL INQUIRY OR TO MAKE A COMMENT PLEASE USE THE CONTACT FORM BELOW AND WE WILL RESPOND AS SOON AS POSSIBLE.</h2>			
<div id="form">
	<form action="" method="post">
		<label for="name">Name:</label>
		<input type="text" name="name" id="name" placeholder="eg. John Doe" required autofocus />

		<label for="name">Email(optional):</label>
		<input type="email" name="email" id="email" placeholder="ex. abc@example.com" />

		<label for="message">Message:</label>
		<textarea name="message" id="message" required></textarea>

		<input type="submit" value="Send Message">
	</form>
</div>

As you can see we have used some of the new Html5 form features, namely the 'email' type and the 'required', 'placeholder' and the 'autofocus' attributes. Setting the type="email" will prompt the user to only enter a valid email address. The placeholder attribute will pre-fill the specified text in the field. The required attribute will prompt the user to fill any field that has this attribute, if the user tries to submit the form without filling it. And finally, the autofocus attribute will pre-select the 'name' input field, in which it is in, when the page loads. To learn more about the new html5 form features, read this article.

At this point I should mention that the older browsers do not support most of these new Html5 features, but that will not cause any problem, as all of these features have fallbacks. For example, in an old browser, like Internet Explorer 8, the placeholder attribute will be ignored and the type="email" will be rendered as type="text".

Next we add some styling for our form

Add the following in the style.css
#form h2{
	color: #0e98d6;
	font-weight: normal;
}

label{
	display: block;
	font-weight: bold;
}


input[type=text], input[type=email], textarea {
	-webkit-transition: all 0.20s ease-in-out;
	-moz-transition: all 0.20s ease-in-out;
	-ms-transition: all 0.20s ease-in-out;
	-o-transition: all 0.20s ease-in-out;
	padding: 5px;
	outline: none;
	border-radius: 3px;
	border: 1px solid #aaa;
	margin: 10px 0 25px 0;
}

input[type="text"], input[type="email"] {
	width: 200px;
}

textarea{
	width: 450px;
	font: 1em Tahoma, Arial;
	min-height: 200px;
	resize:none;
}

input[type=text]:focus, input[type=email]:focus, textarea:focus {
  box-shadow: 0 0 5px rgba(81, 203, 238, 1);
  -webkit-box-shadow: 0 0 5px rgba(81, 203, 238, 1);
  border: 1px solid rgba(81, 203, 238, 1);
}

input[type="submit"]{
	background-color: #0077ad;
	border: none;
	outline: none;
	color: #fff;
	border-radius: 3px;
	padding: 8px 14px;
	margin: 10px 0 0 0;
	cursor: pointer;
}

The only thing worth mentioning in the above code is the Css3 transitioning that we are doing on the input fields and the text area by giving it a blue border when a user clicks in them. The rest is quite basic Css.

We are done with the markup and styling of our form, which also covers our client side validation. However, as you should know, client side validation is only used to enhance user experience and should never be relied on when accepting data, as it can be easily by-passed. Therefore, in the following code we do server-side validation using Php. We will also use the Php mail() function to send the email, after the user's data is verified.

Validation

Below is the Php code that you should put right at the top of contact.php, above: <!doctype html>(as shown in the code below)

Inside contact.php, at the top.
<?php 
if (empty($_POST) === false){

	$mail_to 	= 'abc@yourwebsite.com'; // The email address where you want to receive the email.
	$errors		= array();
	
	$name 		= trim($_POST['name']);
	$email 		= trim($_POST['email']);
	$message 	= trim($_POST['message']);


	if (empty($name) === true || empty($message) === true) {
		$errors[] = 'Name and the Message fields are required.';
	} else {
		if(empty($email) === true){
			$email = 'do-not-reply@yourwebsite.com'; // any email, preferably one of your own domain
		}
        if(ctype_alpha($name) === false){
        	$errors[] = 'Please enter a name with only letters.';
        }
        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            $errors[] = 'Please enter a valid email address.';
        }
		if (strpos($message, '://') || strpos($message, 'www') !== false){
			$errors[] = 'Please do not enter a url in the message.';
		}
	}
	if (empty ($errors) === true) {

		// mail($mail_to, 'Contact From: ' . $name, "$message", 'From: ' . $email);
		header('Location: contact.php?sent');
		exit();
	}
}
?>
<!doctype html>

In the above code we check whether the $_POST variable is set, ie. has the user clicked submit? If it is set then we define the $name, $email and $message variables and store the values submitted by the user for each corresponding field. Next, we check whether the user has supplied a valid name and email address or whether the message field contain any urls. If any of these tests fail, such as if a user enters an invalid email, or a message containing a url, then we store an error in the $errors array and we only send the email to our specified email address($mail_to) when the $errors array is empty.

The reason why we do not allow urls is because a lot of spammers send urls in the message that can be dangerous to click. If a user is genuine and he really has to supply a url, then he can do it in a way that will not make the url immediately clickable. For example, we allow the user to supply google.com but not www.google.com or https://www.google.com, as the last two will make the browser (or the email client) turn them into clickable links which is not what we want.

We also specified do-not-reply@yourwebsite.com, which we use when the user chooses to leave the 'Email' field blank in the form.

Note: We used the mail function to send the email. But it will usually only work when you put your website on a web host. Sending email when developing on localhost can be tricky. So if you are developing locally I suggest that you comment out the mail function for now and remove those comments only when you make your site live.

Next we discuss how we inform the user of any errors or how we inform the users that the message has been send successfully. Also, whenever there is an error, our page refreshes with empty input fields. This can be really frustrating for the user; therefore, in the next section I will also show how to fill the fields with the data that the user provided in the previous attempt.

Showing error and success messages

Below is the code for how we show the error and the success messages. Also how we will fill the form fields when the page refreshes when there is any error.

A part of the updated contact.php
	<div id="form">
		<h2>FOR A GENERAL INQUIRY OR TO MAKE A COMMENT PLEASE USE THE CONTACT FORM BELOW AND WE WILL RESPOND AS SOON AS POSSIBLE.</h2>
		
		<?php 
		if(!empty($errors)){
			echo '<div class="errors">';
			echo '<h3>Errors:</h3>';
			echo '<p>' . implode('</p><p>', $errors) . '</p>';
			echo "</div>";

		}else if(isset($_GET['sent'])){?>
			<div class='success'>Thank you for contacting us.</div>
		<?php
		}
		?>
		<form action="" method="post">
			<label for="name">Name:</label>

			<input type="text" name="name" id="name" placeholder="eg. John Doe" autofocus required <?php if(isset($_POST['name'])){ echo 'value="', htmlspecialchars($_POST['name'], ENT_QUOTES, 'UTF-8'), '"';} ?> />


			<label for="name">Email(optional):</label>

			<input type="email" name="email" id="email" placeholder="ex. abc@example.com"  <?php if(isset($_POST['email'])){ echo 'value="', htmlspecialchars($_POST['email'], ENT_QUOTES, 'UTF-8'), '"';} ?> />


			<label for="url" class="check">Please leave the following field empty</label>

			<input type="text" name="url" id ="url" class="check" autocomplete="off"/>

			
			<label for="message">Message:</label>

			<textarea name="message" id="message" required><?php if(isset($_POST['name'])){ echo htmlspecialchars($_POST['message'], ENT_QUOTES, 'UTF-8');} ?></textarea>

			<input type="submit" value="Send Message">
		</form>
	</div>

So basically, at the top of the form we have added some code, which checks weather the $errors array is empty or not. If it is empty then we echo out all the errors. Also we check if 'sent' is there in the $_GET array, ie. is the string 'sent' there in the url or not (as in contact.php?sent). If it is there then we echo out the success message. Notice that we have specified classes for both of them, so we can use it to style these error messages and success message using css. Also, the code in the input field checks whether $_POST array contains any data for that field or not. If it does, that means that the page has loaded with errors; therefore, we echo out the data that the user had supplied in the previous attempt so that he/she doesn't have to retype everything again. We also make sure that we escaped the data with htmlspecialchars() function before echoing it out, so that this doesn't allow any Xss attacks. For more information about Xss attacks, please read this tutorial.

Next, we add some more css in our style.css file for 'errors' and 'success' class.

Add this in the style.css file
.errors{
	padding: 15px;
	margin: 15px 0;
	background: #ffe5d8;
	border-radius: 5px;
}

.errors h3{
	margin: 5px 0;
	color:#992411;
}

.errors p{
	margin: 0;
}

.success{
	padding: 15px;
	margin: 15px 0;
	background: #aaea8e;
	border-radius: 5px;
}

We are almost done with creating our form, we just need a little protection against spammers that might use our form for sending spam messages. For this you might use CAPTCHA which is quite effective. But I believe CAPTCHAs are not very user friendly and unless your site is getting a lot of visitors, you don't really need them. Therefore, we are going to use a technique that is very user friendly; in fact, the user won't even know that it's there.

The technique works by having an extra input field that is hidden by either Css or JavaScript, that only bots that spammers use are able to see and fill. This is useful because when we receive the POST data, we can check whether this field was filled or not, if it was then it would mean that it was a bot that had filled it and not a genuine user and then we can reject that request and not send the email.

Below is an input field and a label for that field, that you should put in your form. We have assigned both of them with the class 'check' which we can use in our style.css to hide them. Also, we use the 'url' as it's type and also name it 'url', as this will make it more appealing to the bots.

Add this in your form, after the 'email' input field.
<label for="url" class="check">Please leave the following field empty</label>

<input type="text" name="url" id ="url" class="check" autocomplete="off"/>

Now the css to hide these two items.

Put this in the style.css
.check{
	display: none;
}

Now the label and input field are hidden to our users, but visible to the bots that work by reading the source code of the page. However, I should mention that screen readers that people with blindness use, will still be able to read them even if they are hidden by Css; therefore, we have informed them to 'Please leave the following field empty' in the label for the hidden input field. We have also used <label> throughout the form instead of <h4> or something else for the sake of accessibility, as it makes more sense for the screen readers and informs them which input field we are referring to. Also we have set the autocomplete="off" to prevent any browser such as Internet Explorer to automatically filling our hidden input field and causing our clever little technique to fail.

Now completing this system is easy, just put this code at the top of contact.php, right after this line: 'if (empty($_POST) === false){' like so:

Towards the top of contact.php
if (empty($_POST) === false){ // This is just to indicate you where to put the code below, so don't write this again 

	if(!empty($_POST['url'])){
		header('Location: contact.php?sent');
		exit();
	}

If we find that the 'url' index in the POST array was not empty, ie. if we find that the 'user' had entered something in the field that was supposed to be hidden, then we redirect the user to the success page and say that the message was sent, without actually sending the email. This will fool the bot into thinking that the spam message was sent. *Great Success!*

Right, so we are done with creating our form and providing it with some level of spam proofing. Next we look at how we can display our email and phone number securely, using the Php GD library.

Showing our Email and our Phone number securely

GD library is a very useful tool, and you can do a lot of interesting things with images using it. We will only use it to convert our email address and phone number that we want the users to see, into images, so that it is harder for spammers to retrieve and abuse them. We will have to create a separate file called image.php and create our images over there. For this we will also have to download a True type font, such as Verdana that I have used in this tutorial. Therefore, I've downloaded the font file verdana.ttf from here. If you want to use some other font, google around for that font and download it and save it in the same directory as contact.php, but make sure it is a True type font with '.ttf' extension.

Before we can work on creating the images, first I'll show how to insert the images in the Contact us page.

Inside contact.php with updated div with id="details"

<div id="details">
	<h2>Our contact details</h2>

	<h4>Email us:</h4>
	<span><img src="image.php?string=email"></span><br><br>

	<h4>Call us:</h4> 
	<span><img src="image.php?string=number"></span><br><br>
</div>

Normally when you want to insert an image in a page you use the <img> tag and use 'src' to refer to the location of an image. In this we do the same, but we also specify 'string=email' and 'string=number' according to what we want. We will use this to create either an image of our email address or that of our number, which we will define and create in the image.php file.

Over to our image.php
<?php 
header("Content-type: image/png"); // Setting the Content-type to image/png.

if($_GET['string'] == 'email'){
	$string 	= "abc@example.com"; // Replace abc@example.com with your email.
}else if($_GET['string'] == 'number'){
	$string 	= "122131"; // Replace 122131 with your number
}else{
	$string 	= "No string specified"; // We are not going to use this.
}

$font_path 		= 'verdana.ttf'; // Defining the path to our downloaded Truetypefont. 
$font_size 		= 10; // Setting the font size to 10, after doing some experimenting.

$string_length 	= strlen($string); // Getting the string length to be used in getting the width of the image.
$image_height 	= imagefontheight($font_size); // Estimating the height of the image using imagefontheight
$image_width 	= imagefontwidth($font_size) * $string_length; // Estimating the width of the image using imagefontwidth


$image 			= imagecreate($image_width,$image_height); // Setting our estimated width and height of the image

imagecolorallocate($image, 255,255,255); // Background color (255, 255, 255) is rgb representing white color or #fff

$color			= imagecolorallocate($image, 34, 34, 34); // setting the color of the text. (34,34,34) is equivalent to #222 that we have used throughout our page.

// Output the image
imagefttext($image, $font_size, 0, 0, $image_height-3, $color, $font_path, $string); // Creating the image

imagepng($image); // Finaly displaying the $image image
imagedestroy($image); // Clearing the memory. (not required)
?>

Explanation of the above code: First we specify the content type of the page to be an image and that of png type. Next we create the $string variable depending on what is required. In our example, in the contact.php when we specify the src as 'image.php?string=email', the $string in image.php becomes 'abc@example.com', if we specify it to be 'image.php?string=number' then $string becomes '122131'. Needless to say, but you can change abc@example.com to your email and '122131' into your phone number, that you want to show.

The rest of the code is specific to GD library functions. But what I should mention and what you might want to change is the following:

  • $font_path is the path to the TrueTypeFont that you should download for the font that you want to use, like Tahoma, Arial, Grenada or any other font for which you can find a '.ttf' file.
  • $font_size is as you can imagine is the size of the font. I got the value of 10 after experimenting, so you can do the same and see which size matches the size of the text on your page.
  • The first time when we use imagecolorallocate() function we set the background of the image to white by supplying the rgb color code for white, you can change this to whatever color you want.
  • Next when we use imagecolorallocate() we specify the color of the text of the string that we want to use. In our case we used #222 color in our style.css, for which the rgb color code is (34, 34, 34), again change this if you have used some other color.

The rest of the code that we did not discuss includes setting the width and height of the image, creating an image and then displaying the image. To learn more about the Php GD library, I suggest these resources that helped me in understanding it.


Now we are done with showing our email and phone numbers in a secure way. Next we look at the big one, the Google Maps API!

Showing our location using Google Maps API

We need to create a div in our contact.php file in which we will display our map. We will also show our address in the form of text, but you can use the GD library technique we just discussed and show it as an image, although I don't think it is required. So below is our updated div with id="details".

Inside contact.php
<div id="details">
	<h2>Our contact details</h2>
	<h4>Email us:</h4>
	<span><img src="image.php?string=email"></span><br><br>

	<h4>Call us:</h4> 
	<span><img src="image.php?string=number"></span><br><br>
	
	<h4>Our address:</h4> 
	<span>Stonehenge, Amesbury, Wiltshire, Uk</span><br><br>
	<div id="map"></div>
</div>

To display the map, all we have done is created a div with an id="map". However we also need to add few lines in our head section of the contact.php

Add the following code in the head section of contact.php
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript" src="js/map.js"></script>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />

In the above code, we create two script elements. First one gets the Google Maps API library stored in the Google's server which will enable us to create the map, and the second links to the map.js file in js folder which we are going to create soon. We also put a meta tag which disables the zoom-to-pinch feature of IPhone.

Now we are going to do all the work in map.js, but before that lets add some css for our map.

Add this in style.css
#map{
	width: 100%;
	height: 235px;
}

We've simply set the width to be 100% and height 235px, but you can choose your own.

Now create a new folder called 'js' and create a file called map.js in it and add the following code.

map.js
google.maps.visualRefresh = true;
(function() {
	window.onload = function() {

		var mapDiv = document.getElementById('map');
		var latlng = new google.maps.LatLng(40.714, -74.005);

		var options = {
			center: latlng,
			zoom: 15,
			mapTypeId: google.maps.MapTypeId.ROADMAP,
			backgroundColor: '#fff',
			mapTypeControl: true,
			mapTypeControlOptions: {
				style: google.maps.MapTypeControlStyle.DROPDOWN_MENU,
			},

			scaleControl: true
		};

		var map = new google.maps.Map(mapDiv, options);
	}
})();

The above code will display a map centered on New York, like this:

screen3.png

It is actually very simple what we have done above; in fact, most of the code above is for the customization that I chose for the map and is not really required. We will discuss how you can show and mark your location instead of New York, but first I'll go over the above code:

  • google.maps.visualRefresh = true; - This line is just there so we can use the new and more refreshed look of Google Maps. Try removing this line or commenting it out to see how things like icons on the map, or the font of the drop down option or the road lines change.
  • Next we create and encapsulated function that loads an anonymous function when the window has loaded. You should know about this if you have any experience with JavaScript, if not then don't worry about it.
  • var mapDiv - This line just selects our div with the id="map" and stores it in the mapDiv variable which we use later.
  • var latlng - This is another variable that we create which we use later to center the map. We used (40.714, -74.005) for now which are the latitude/longitude coordinates of the New York city.
  • var options - Now this is necessary, as in this we will include all our customization options. There are many options that you can include in it, but 3 are required for the map to work, which are 'center', 'zoom' and 'mapTypeId'.
  • center - This is used to specify the center of the map, when it loads. We have used the latlng variable that we created to specify the center to be the New York city.
  • zoom - The zoom level can range from 0 - 23. 0 will display the whole world and 23 will display a really zoomed in version of the location, if the data is available. I've it to 15.
  • mapTypeId - This is the default map type that you want to show when the page loads. It is the last of the 3 required options that you should have in the options variable. I've set it's value to: google.maps.MapTypeId.ROADMAP to show a regular road map. Following is the what I got from the Google Maps API documentation regarding the other options for mapTypeid:
  • MapTypeId.ROADMAP displays the default road map view.
  • MapTypeId.SATELLITE displays Google Earth satellite images.
  • MapTypeId.HYBRID displays a mixture of normal and satellite views.
  • MapTypeId.TERRAIN displays a physical map based on terrain information.
  • The backgroundColor is used to specify the color that is displayed when you pan around and wait for the map to load. The default is a grey color but I've set it to #fff which is white.
  • The mapTypeControlOptions is used to change the properties of the Map type Control that you can see on the top right of the map. I've only used this to change the style of the Map type Control to a drop down list instead of the default horizontal list.
  • Lastly in our options variable, I set the scaleControl to true, which will display the scale of the map that you can see at the bottom of it.
  • Finally, we create the map using: var map = new google.maps.Map(mapDiv, options); where we specify our div in which we want the map to be in and the options variable that contains how we want to map to be.

The above code will create a pretty good looking map centered over New York. But to be able to center the map on our exact location and also put a marker on it we need to first get the latitude/longitude coordinates of that location. For this we can use something called Reverse Geocoding, which is part of the GoogleMapsAPI, but because it is somewhat complex I am going to use a different technique instead.

Putting the marker on our location

To be able to center the map at our location and put a marker on it, we will have to go through some steps. First, we will create a button under the div with id="map" which when clicked will display the coordinates of the location that is centered on the map. So add the following code under <div id="map"></div>"

Inside contact.php under the map div
<input type="button" value="getCoordinates" id="getCoordinates" />

Now in the map.js enter the following code under 'var map = new google.maps.Map(mapDiv, options);'(as indicated in the code).

Inside map.js
var map = new google.maps.Map(mapDiv, options); // This is just to show where to put the code below, so don't put this line again in your code.

google.maps.event.addListener(map, 'click', function(e) {
	getAddress(e.latLng);
});

document.getElementById('getCoordinates').onclick = function() {
	alert('Current center is ' + map.getCenter());
}

Now in the contact.php page, use pan and zoom to get to the location you want at the center of the map. When the location is at the center, hit the 'getCoordinates' button and you will get an alert box with the coordinates of the center that is in the map, which should be your location. Note down the coordinates (approximate to 5 or 6 decimal places) and remove or comment out the code that you have just created. The page with the alert box should look like this:

screen11.png

Now to create our marker for our location, you will have to add one final code in the map.js file, again under: 'var map = new google.maps.Map(mapDiv, options);'(as indicated in the code).

Inside map.js
var map = new google.maps.Map(mapDiv, options);

var marker = new google.maps.Marker({
position: new google.maps.LatLng(51.178859, -1.826047),
map: map,
});

Also, change the var latlng with the new coordinates of your location to also center the map over there.

Inside map.js.
var latlng = new google.maps.LatLng(51.178859, -1.826047);

And that's it, your final map and map.js should look like this:

screen22.png Complete map.js
google.maps.visualRefresh = true;
(function() {
	window.onload = function() {

		var mapDiv = document.getElementById('map');
		var latlng = new google.maps.LatLng(51.178859, -1.826047);

		var options = {
			center: latlng,
			zoom: 21,
			mapTypeId: google.maps.MapTypeId.ROADMAP,
			mapTypeControl: true,
			backgroundColor: '#fff',
			mapTypeControlOptions: {
				style: google.maps.MapTypeControlStyle.DROPDOWN_MENU,
			},

			scaleControl: true
		};

		var map = new google.maps.Map(mapDiv, options);

		// Adding a marker to the map
		var marker = new google.maps.Marker({
		position: new google.maps.LatLng(51.178859, -1.826047),
		map: map,
		});

		// google.maps.event.addListener(map, 'click', function(e) {
		// // Getting the address for the position being clicked
		// getAddress(e.latLng);
		// });


		// document.getElementById('getCoordinates').onclick = function() {
		// 	alert('Current center is ' + map.getCenter());
		// }

	}
})();

I think this is the best amount of features that a map in a Contact us page need. But there are many other things you can add or change in your map, like changing the style and positions of map control, using poly lines and triangles to show locations, or using custom markers instead of the default. There is also the ability to have a 'Get directions' functionality that will ask the user to enter their location and then you can provide the best routes and directions for them to reach your location. To learn more about this and other features of Google Maps API, I suggest you read their documentation.

Below is the final contact.php file.

Final and complete contact.php
<?php 
if (empty($_POST) === false){

	if(!empty($_POST['url'])){
		header('Location: contact.php?sent');
		exit();
	}

	$mail_to 	= 'abc@yourwebsite.com'; // The email address where you want to recieve the email
	$errors		= array();
	
	$name 		= trim($_POST['name']);
	$email 		= trim($_POST['email']);
	$message 	= trim($_POST['message']);


	if (empty($name) === true || empty($message) === true) {
		$errors[] = 'Name and the Message fields are required.';
	} else {
		if(empty($email) === true){
			$email = 'do-not-reply@yourwebsite.com'; // any email, preferably one of your own domain
		}
        if(ctype_alpha($name) === false){
        	$errors[] = 'Please enter a name with only letters.';
        }
        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            $errors[] = 'Please enter a valid email address.';
        }
		if (strpos($message, '://') || strpos($message, 'www') !== false){
			$errors[] = 'Please do not enter a url in the Message.';
		}
	}
	if (empty ($errors) === true) {

		mail($mail_to, 'Contact From: ' . $name, "$message", 'From: ' . $email);
		header('Location: contact.php?sent');
		exit();
	}
}
?>
<!doctype html>
<html lang="en">
<head>
	<title>Contact us</title>
	<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
	<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />

	<link rel="stylesheet" type="text/css" href="style.css">

	<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
	<script type="text/javascript" src="js/map.js"></script>
</head>
<body>
<div id="container">
	<div id="form">
	<h2>FOR A GENERAL INQUIRY OR TO MAKE A COMMENT PLEASE USE THE CONTACT FORM BELOW AND WE WILL RESPOND AS SOON AS POSSIBLE.</h2>
	
	<?php 
	if(!empty($errors)){
		echo '<div class="errors">';
		echo '<h3>Errors:</h3>';
		echo '<p>' . implode('</p><p>', $errors) . '</p>';
		echo "</div>";

	}else if(isset($_GET['sent'])){?>
		<div class='success'>Thank you for contacting us.</div>
	<?php
	}
	?>
	<form action="" method="post">
		<label for="name">Name:</label>

		<input type="text" name="name" id="name" required placeholder="eg. John Doe" autofocus <?php if(isset($_POST['name'])){ echo 'value="', htmlentities($_POST['name'], ENT_QUOTES, 'UTF-8'), '"';} ?> />


		<label for="name">Email(optional):</label>

		<input type="email" name="email" id="email" placeholder="ex. abc@example.com"  <?php if(isset($_POST['email'])){ echo 'value="', htmlentities($_POST['email'], ENT_QUOTES, 'UTF-8'), '"';} ?> />


		<label for="url" class="check">Please leave the following field empty</label>

		<input type="text" name="url" id ="url" class="check" autocomplete="off"/>

		
		<label for="message">Message:</label>

		<textarea name="message" id="message" required><?php if(isset($_POST['name'])){ echo htmlentities($_POST['message'], ENT_QUOTES, 'UTF-8');} ?></textarea>


		<input type="submit" value="Send Message">
	</form>

	</div>
	<div id="details">
		<h2>Our contact details</h2>

		<h4>Email us:</h4>
		<span><img src="image.php?string=email"></span><br><br>

		<h4>Call us:</h4> 
		<span><img src="image.php?string=number"></span><br><br>
		
		<h4>Our address:</h4> 
		<span>Stonehenge, Amesbury, Wiltshire, Uk</span><br><br>
		<div id="map"></div>
<!-- 		<input type="button" value="getCoordinates" id="getCoordinates" /> -->
	</div>
	<div class="clear"></div>

</div>
</body>
</html>

Conclusion

I hope this was a useful tutorial for you. The source code is available in a link at the top and so does the demo. If you have any questions or comments regarding this tutorial then please share it in the comments below. Thank you for reading.

Follow us on Twitter!
comments powered by Disqus