Skip to content
PHP Logo

What are some best practices for creating an online form using PHP to ensure successful email delivery?

When creating an online form using PHP, it is important to properly set up the email delivery functionality to ensure successful delivery of form submissions. One best practice is to use a reliable and secure email service provider to send the emails. Additionally, make sure to validate user input to prevent malicious code injection and properly sanitize the data before sending it via email.

php
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $name = $_POST['name'];
    $email = $_POST['email'];
    $message = $_POST['message'];

    $to = 'recipient@example.com';
    $subject = 'Form Submission';
    $message = 'Name: ' . $name . "\r\n" . 'Email: ' . $email . "\r\n" . 'Message: ' . $message;

    $headers = 'From: ' . $email;

    if (mail($to, $subject, $message, $headers)) {
        echo 'Email sent successfully.';
    } else {
        echo 'Email sending failed.';
    }
}
?>