What are some best practices for allowing users to choose email recipients through a drop-down menu in a PHP form?
When allowing users to choose email recipients through a drop-down menu in a PHP form, it is important to properly sanitize and validate the user input to prevent any security vulnerabilities such as SQL injection or cross-site scripting attacks. One way to achieve this is by using PHP's filter_var function to sanitize the input and only allowing predefined values in the drop-down menu options.
// Example PHP code snippet for allowing users to choose email recipients through a drop-down menu
// Define an array of predefined email recipients
$emailRecipients = array(
"recipient1@example.com" => "Recipient 1",
"recipient2@example.com" => "Recipient 2",
"recipient3@example.com" => "Recipient 3"
);
// Validate and sanitize the user input
if(isset($_POST['recipient']) && array_key_exists($_POST['recipient'], $emailRecipients)) {
$selectedRecipient = filter_var($_POST['recipient'], FILTER_SANITIZE_EMAIL);
// Use $selectedRecipient as the email recipient in your email sending function
} else {
// Handle invalid input error
echo "Invalid recipient selected";
}
// HTML form with drop-down menu for selecting email recipients
echo "<form method='post'>";
echo "<select name='recipient'>";
foreach($emailRecipients as $email => $name) {
echo "<option value='$email'>$name</option>";
}
echo "</select>";
echo "<input type='submit' value='Send Email'>";
echo "</form>";