I recently had my site hacked, with the main index file being overwritten (nothing else was touched). I'm assuming they hijacked my form input.
Are there any vulnerabilities in the code or does this look to be safe now?
<?php
$myemail = "[email protected]";
$subject = "Form Submitted";
$name = $_POST['name'];
$email = $_POST['email'];
$number = $_POST['number'];
$comments = $_POST['comments'];
$feedback = "";
$message = <<<EMAIL
Name: $name
Email: $email
Message:
$comments
EMAIL;
/////////////////////////////////////////////////////////////////////////////
// Form input validation
/////////////////////////////////////////////////////////////////////////////
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "Name is required";
$feedback = "";
} else {
$name = test_input($_POST["name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$nameErr = "Only letters and white space allowed";
$feedback = "";
} else {
$nameErr = "";
}
}
if (empty($_POST["comments"])) {
$commentsErr = "Message is required";
$feedback = "";
} else {
$comments = test_input($_POST["comments"]);
$commentsErr = "";
}
} // End input validation
/////////////////////////////////////////////////////////////////////////////
// Successful form submission
// Neither (name and nameErr) nor (comments and commentsErr) could possibly
// be empty strings. This prevents the form from being submitted as soon as
// the page is loaded. It also clears all fields when the form is successful.
// All field contents will remain until form is successfully submitted.
/////////////////////////////////////////////////////////////////////////////
if($commentsErr == "" && $nameErr == "" && $name != "" && $comments != ""){
mail($myemail,$subject,$message);
$feedback = "Thanks for contacting us ! We'll be in touch soon.";
$_POST['name'] = "";
$_POST['email'] = "";
$_POST['number'] = "";
$_POST['comments'] = "";
}
// Function strips any dangerous characters from input
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>