Created
September 28, 2015 21:59
-
-
Save TimSC/375397c9ad8c83bc26d6 to your computer and use it in GitHub Desktop.
Generic php contact form with UTF-8 encoding of email
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!-- You may use this under the terms of https://creativecommons.org/publicdomain/zero/1.0/ --> | |
<?php | |
if (isset($_POST["action"])) | |
{ | |
$ok = true; | |
$errorMsg = Null; | |
$from_email = $_POST["email"]; | |
if (!filter_var($from_email, FILTER_VALIDATE_EMAIL)) { | |
$ok = false; | |
$errorMsg = "Invalid email format"; | |
} | |
if($ok) { | |
$domain = array_pop(explode("@",$from_email)); | |
if (!checkdnsrr($domain, 'MX')) { | |
$ok = false; | |
$errorMsg = "Email domain is not valid"; | |
} | |
} | |
if($ok) { | |
if (strlen($_POST["subject"])==0) { | |
$ok = false; | |
$errorMsg = "Subject cannot be empty"; | |
} | |
} | |
if($ok) { | |
if (strlen($_POST["sender"])==0) { | |
$ok = false; | |
$errorMsg = "Sender name cannot be empty"; | |
} | |
} | |
if($ok) { | |
if (strlen($_POST["message"])==0) { | |
$ok = false; | |
$errorMsg = "Message cannot be empty"; | |
} | |
} | |
if($ok) { | |
$to = "[email protected]"; | |
$from_user = "=?UTF-8?B?".base64_encode($_POST["sender"])."?="; | |
$subject = "=?UTF-8?B?".base64_encode($_POST["subject"])."?="; | |
$message = $_POST["message"]; | |
$message .= "\r\nSender IP address: ".$_SERVER["REMOTE_ADDR"]."\r\n"; | |
$messageEncoded = $message; | |
$headers = 'From: '.$from_user.' <'.$from_email.'>'. "\r\n" . | |
"MIME-Version: 1.0" . "\r\n" . | |
"Content-Transfer-Encoding: 8bit\r\n". | |
"Content-type: text/plain; charset=\"UTF-8\"" . "\r\n"; | |
$mailResult = mail($to, $subject, $messageEncoded, $headers); | |
if(!$mailResult) { | |
$ok = false; | |
$errorMsg = "Failed to send email!"; | |
} | |
} | |
} | |
?> | |
<!DOCTYPE html> | |
<html> | |
<head> | |
<meta charset="UTF-8"> | |
<title>Contact Form</title> | |
</head> | |
<body> | |
<div style="width:800px;"> | |
<h1>Contact Me</h1> | |
<hr/> | |
<?php | |
if (!isset($_POST["action"])) | |
{ | |
?> | |
<form method="POST"> | |
<p>Your name: <input name="sender" type="text"/><br/> | |
Your email: <input name="email" type="text"/><br/> | |
Subject: <input name="subject" type="text"/><br/> | |
Message:<br/> | |
<textarea name="message" style="width: 600px; height: 150px;"></textarea><br/> | |
<input name="action" type="submit" value="Send"/> | |
</p> | |
</form> | |
<?php | |
} else { | |
if($ok) { | |
?> | |
<p>Message sent!</p> | |
<?php | |
} else { | |
?> | |
<p><?php echo $errorMsg;?></p> | |
<?php | |
} | |
} | |
?> | |
</div> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment