简体   繁体   中英

PHP Mail - Sanitizing and Validating for Basic Form

I'm looking for the safest and most effective way to use php mail for a basic form.

I have the below code, and it seems to work decently, but I'm very new to php and would like input on if there's better ways to execute this. Should I be doing more to help protect from injection? Or do I even need to worry about that with plain text email?

Right now I'm sanitizing the email field. Should I sanitize all fields? I figured out how to validate the email too, but the problem with that is I don't like it if a legit user writes a super long message and accidentally inputs a mistake in his email, then php gives a non-valid email error and wipes away the whole message. I'd rather just sanitize it and the message still gets sent. I do have Jquery validate in place so that helps too.

I'm open to any advice on how to improve this form, or if you see anything I did wrong, please let me know! Thank you.

<?php
if (isset($_POST['submit'])) {


$send_to = "receiver@domain.com";
$subject = "Contact Page Form";
$headers = 
'From: "Sender Name" <sender@domain.com>' . "\r\n" .
'Reply-To: ' . $_POST['name'] . '<' . $_POST['email'] . '>' . "\r\n" .
'Content-type: text/plain; charset=iso-8859-1';
'X-Mailer: PHP/' . phpversion();
$success = "<p class=\"formsuccess\">Thank you. We received your message!</p>";


$name = $_POST['name'];
$email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);
$phone = $_POST['phone'];
$message = $_POST['message'];

$content = "
Name: $name
Email: $email
Phone: $phone

Message: $message
";

mail($send_to,$subject,$content,$headers);
echo $success;

} else {
?>
<form id="contactform" method="post">

NAME: <input type="text" name="name" required>
EMAIL: <input type="email" name="email" required>
PHONE: <input type="tel" name="phone" required>
MESSAGE:<textarea name="message" required></textarea>

<button type="submit" name="submit">Submit</button>

</form>
<script>
$("#contactform").validate();
</script>
<?php } ?>

If validation fails on the server side, you just need to repopulate the form with submitted values:

NAME: <input type="text" name="name" value="<?php echo $name; ?>" required>

Set the variables to default values before your submission check to avoid 'undefined variable' errors.

Next, if you're worried about validity, you should avoid calling mail() directly - your script as it stands is vulnerable to header injection attacks and all kinds of corruption. Use a library like PHPMailer (which you already tagged the question with) to do it correctly and follow the examples provided for processing forms.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM