What best practices should be followed when using checkboxes to select email recipients in PHP forms?
When using checkboxes to select email recipients in PHP forms, it is important to ensure that the form data is properly sanitized and validated to prevent any security vulnerabilities such as SQL injection or cross-site scripting attacks. Additionally, the PHP code should handle the selected checkboxes correctly to ensure that the email recipients are accurately identified and included in the email sending process.
// Sanitize and validate the form data
$selectedRecipients = isset($_POST['recipients']) ? $_POST['recipients'] : array();
$selectedRecipients = array_map('intval', $selectedRecipients); // sanitize as integers
// Handle the selected checkboxes
$recipientsList = array(
1 => 'recipient1@example.com',
2 => 'recipient2@example.com',
3 => 'recipient3@example.com'
);
$selectedEmails = array();
foreach ($selectedRecipients as $recipientId) {
if (isset($recipientsList[$recipientId])) {
$selectedEmails[] = $recipientsList[$recipientId];
}
}
// Send email to selected recipients
foreach ($selectedEmails as $email) {
// Send email using mail() function or PHPMailer, SwiftMailer, etc.
}