What potential security risks are associated with the use of the mail function in PHP for form submissions?

The potential security risks associated with using the mail function in PHP for form submissions include injection attacks, spamming, and unauthorized access to the server. To mitigate these risks, it is recommended to sanitize and validate user input before using it in the mail function.

// Sanitize and validate user input before using it in the mail function
$name = filter_var($_POST['name'], FILTER_SANITIZE_STRING);
$email = filter_var($_POST['email'], FILTER_VALIDATE_EMAIL);
$message = filter_var($_POST['message'], FILTER_SANITIZE_STRING);

// Check if input is valid before sending the email
if ($name && $email && $message) {
    $to = 'recipient@example.com';
    $subject = 'Form Submission';
    $headers = 'From: ' . $email;

    // Send the email
    mail($to, $subject, $message, $headers);
} else {
    echo 'Invalid input, please try again.';
}