This code processes a basic contact form with a name, email and message. It also asks for a code to be typed in. The data is then transformed to avoid malicious placing of HTML script on the server, and if the name and email are valid, sent to my email.
Is this code really secure against the attempt to place malicious HTML code?
<!DOCTYPE html>
<html>
<head>
<title>Contact Form</title>
<meta charset="utf-8">
<link rel="stylesheet" href="css/site.css" >
<link rel="stylesheet" href="css/font-awesome-4.4.0/css/font-awesome.min.css" >
</head>
<body>
<?php
$nameErr = $emailErr = $messageErr = $errors = "";
$name = $email = $message = "";
$myemail = '[email protected]';
if (empty($_POST["name"])) {
$nameErr = " (required)";
} else {
$name = test_input($_POST["name"]);
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$nameErr = " only letters and white space allowed";
}
}
if (empty($_POST["email"])) {
$emailErr = " (required)";
} else {
$email = test_input($_POST["email"]);
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = " invalid email format";
}
}
if (empty($_POST["message"])) {
$messageErr = " (required)";
} else {
$message = test_input($_POST["message"]);
}
if(empty($nameErr) && empty($emailErr) && empty($messageErr))
{
if (strtolower($_POST['code']) != 'mycode') {die('Wrong access code');}
$to = $myemail;
$email_subject = "Contact form submission - $name";
$email_body = "Name: $name \n " . "Email: $email\n\n $message";
$headers = "From: $myemail\n";
$headers .= "Reply-To: $email";
mail($to,$email_subject,$email_body,$headers);
$message = "Thank you for your message! :)";
$name = " ";
$email = " ";
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<div>
<label for="name">Name:</label>
<input type="text" name="name" <?php echo "value = " . $name;?>>
<span><?php echo $nameErr;?></span>
</div>
<div>
<label for="mail">E-mail:</label>
<input type="email" name="email" <?php echo "value = " . $email;?>>
<span><?php echo $emailErr;?></span>
</div>
<div>
<label for="msg">Message:</label>
<textarea name="message"><?php echo $message;?></textarea>
<span><?php echo $messageErr;?></span>
</div>
<div>
<label for="code">Access code:</label>
<input type="text" name="code">
<i class="fa fa-arrow-left"></i> type <span class="em4">mycode</span> here
</div>
<div class="button">
<button type="submit">Send</button>
</div>
</form>
<br>
<footer id="foot01"></footer>
<script src="css/script.js"></script>
</div>
</body>
</html>