Are there best practices for handling variable return paths in PHP mail forms?

Handling variable return paths in PHP mail forms can be achieved by dynamically setting the "From" header in the email using the user's input. This allows the email to be sent back to the user's provided email address. It is important to sanitize and validate the user input to prevent any potential security vulnerabilities.

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $to = "your@email.com";
    $subject = "Contact Form Submission";
    $message = $_POST["message"];
    $headers = "From: " . $_POST["email"];

    if (filter_var($_POST["email"], FILTER_VALIDATE_EMAIL)) {
        mail($to, $subject, $message, $headers);
        echo "Email sent successfully";
    } else {
        echo "Invalid email address";
    }
}
?>