(PHP) Simple e-mail contact form.

By | May 21, 2012

A simple contact form, just for reference. Will add more info later on…

if (isset($_POST['submit'])) {

	$name = $_POST['name']; //name of sender
	$email = $_POST['email']; //e-mail of sender
	$email = stripslashes($email);
	$subject = $_POST['subject']; //e-mail subject 
	$subject = str_replace(array("\r\n","\r","\n"), "", $subject); //remove any linebreaks to keep from code injections

	$message = $_POST['message']; // e-mail message
	$message = str_replace(array("\r\n", "\r"), "\n", $message); // fix line-breaks
	$message = stripslashes($message);

	$headers = "From:$name<$email>\r\n";
	$headers .= "Return-path: <$email>\r\n";
	$headers .= "Content-type: text/plain; charset=UTF-8\r\n";
	$headers .= "Content-Transfer-Encoding: 8bit\r\n";
	$to = 'myadress@mydomain.com'; //recipients e-mail adress

	//validate email and name variables
	if (!filter_var($email, FILTER_VALIDATE_EMAIL))
		echo 'not a valid e-mail adress';
	if (preg_match('/[^a-z åäöÅÄÖüÜ _-]/i', $name))
		echo 'not a valid name format';

	//send the email
	$send = mail($to, $subject, $message, $headers);
	if ($send)
		echo 'email sent';
		echo 'something went wrong, email not sent';

	<meta charset="utf-8">
	<form action="" method="post">
		<input type="text" name="name"/>
		<input type="text" name="email"/>
		<input type="text" name="subject"/>
		<textarea name="message"/></textarea>
		<input type="submit" name="submit"/>

Leave a Reply

Your email address will not be published. Required fields are marked *