I've created a web form with PHP, and I'd like to allow someone to select from a list of recipients in a select box. Is this possible with PHP? I know that you could place the emails as the value of the option, but is there a more secure method? Thanks.
EDIT:
Should I do something like:
if ($_POST['emailTo']=="president")
{
$to = president@example.com;
else if ($_POST['emailTo']=="vice-president")
{
$to = vPresident@example.com;
}
mail("$to", "subject", message, $from);
Your main concern is abuse - a malicious user can change the POST request and cause your code to send email to any address they choose.
You should secure your application by including in your form not the email addresses themselves but instead references to the email addresses. Your code will then need to translate the submitted value into an email address
A trivial example would be to set the select box options to integer values. Your code could translate the selected option to an email address via a lookup of some form.
HTML:
<select name="recipient">
<option value="1">Example 1</option>
<option value="2">Example 2</option>
<option value="3">Example 3</option>
</select>
PHP:
switch ($_POST['recipient') {
case 1:
$emailAddress = 'one@example.com';
break;
case 2:
$emailAddress = 'two@example.com';
break;
case 3:
$emailAddress = 'three@example.com';
break;
}
If you want to have it go to multiple emails just add a form with check boxes for all the email addresses. Allow users to check addresses on the list and then add them to the recipient/send to variable. Make them comma separated. I have an example of one I built once sort of like what your asking. Let me find it.
EDIT: Found it...
// EDIT THE LINES BELOW AS REQUIRED
$email_to = "EMAIL1, EMAIL2, EMAIL3";
$email_subject = "Someone Signed Up! :)";
In the $email_to section just have the checked emails input into that field. If you want my entire script I can give it to you. You'll just need to make a form input for that field.
As noted by someone else, security is an issue. If its just someone wanting this function for like a mailer system you could probably be ok, but if its a free reign user kind of thing you might want to limit the use of the form. Only allow 3 emails to be checked, or have 3 fields that can be typed into that way only so many emails can be sent at once.
In the PHP code that sends the email, you could create an array of valid recipient emails and if the selected email by the user is in the array then send the email, if not, return an error. So you would have
$valid_emails = array("validemail1@email.com", "validemail2@email.com", "validemail3@email.com", "validemail4@email.com");
if(in_array($_REQUEST['recipient_email'], $valid_emails))
{
send_email($_REQUEST['recipient_email']);
}
else
{
return_error("Invalid recipient email.");
}