How to make a Contact Us page in PHP

From Knowledge Kitchen
Jump to navigation Jump to search


This example shows how to create a common type of "Contact Us" web page.

  1. An HTML form feeds data to a PHP script.
  2. The PHP script sends an email to a hard-coded recipient.
  3. A "thank you" page is displayed once the email has been sent.


HTML page

Save this in a file, let's call it index.html. This page displays a form that the site visitor fills out.

<!doctype html>
 <html>
 	<head>
 		<title>Contact Us</title>
 	</head>
 	<body>
 		<h1>Contact Us</h1>
 		<p>Please enter your message:</p>
 
 		<form action="contact_us.php">
 			<label for="name">Your name:</label>
 			<input type="text" name="name" id="name" />
 
 			<br />
 
 			<label for="email">Your email:</label>
 			<input type="text" name="email" id="email" />
 
 			<br />
 
 			<label for="subject">Your subject:</label>
 			<input type="text" name="subject" id="subject" />
 
 			<br />
 
 			<label for="message">Your message:</label>
 			<textarea id="message" name="message"></textarea>
 
 			<br />
 			<input type="submit" value="Send!" />
 
 	</body>
 </html>


PHP script

Save this in a file, let's call it contact_us.php. This script receives the data that the user filled out in the form on index.html, and sends it in an email to the site administrator. Once that's done, it redirects the visitor's browser to a "thank you page" called thanks.html.

<?php
 
 //store the to address in a simple variable
 $to = 'webmaster@mailinator.com';
 
 $subject = $_GET['subject'];
 
 $message = $_GET['message'];
 
 $headers = <<<END
 From: {$_GET['name']} <{$_GET['email']}>
 Reply-To: {$_GET['email']}
 END;
 
 //send an email to the recipient
 mail($to, $subject, $message, $headers);	
 
 //redirect to thank you page
 header("Location: thanks.html");
 
 ?>

Thank You HTML page

Save this in a file, let's call it thanks.html. This page displays a "thank you" message to the site visitor.

<!doctype html>
 <html>
 	<head>
 		<title>Thank You!</title>
 	</head>
 	<body>
 		<h1>Thank you!</h1>
 		<p>We will definitely read your email at some point.</p>
 
 		<p>
 			<a href="./">Why not send another email to us?</a>
 		</p>
 
 	</body>
 </html>


What links here