Greetings everyone.

i have a number of check box's, a message text area and a submit button. Depending on what box is checked it will send the message to that email address.

Here is the code for the form:

<form method="POST" name="myform" action="checked.php">

<input type="checkbox" name="emails[]" value="user1@domain.com" />

<input type="checkbox" name="emails[]" value="user2@domain.com" />

<input type="checkbox" name="emails[]" value="user3@domain.com" />

 <textarea></textarea>

<input type="image" src="images/submit.jpg" alt="Submit button">

</form>

i would like to know now, how i would go about writing the php code for this in the simplest way, maybe not using a load of if statements? because i am going to be having about a dozen check box's each holding a different email address.

Many thanks!

this is the php code i currently have:

<?php

 
if( in_array("one", $_POST["send"]) )
{
 mail("user@contact.com", $message);

}
 
if( in_array("two", $_POST["send"]) )
{
 mail(user@contact.com", $message);

}
 
if( in_array("three", $_POST["send"]) )
{
 mail("user@contact.com", $message);

}
 
if( in_array("four", $_POST["send"]) )
{
 mail("user@contact.com", $message);

}
 
?>

You are sending the email addresses as the values of the selected entry. So, you can just loop over the results:

<?php
if(isset($_POST['emails']) && is_array($_POST['emails'])
{
   foreach($_POST['emails'] as $email)
   {
      mail($email, $message);
   }
} else {
  echo "No email addresses to send to!";
}
?>

If the code is public facing (accessible to the public) you don't want the email address concealed in the form because spammers have web crawlers that go looking for email addresses found on pages and send them spam like crazy. Also, if the email addresses originate from other users, you should add code someplace that verifies the entered address is a validly formed email address.

hello madcoder, thanks very much, this is much simpler, however i get an error:

Parse error: syntax error, unexpected '{' .... on line 3

Oh, I missed a parenthesis at the end of line 2 to complete the if().

if(isset($_POST['emails']) && is_array($_POST['emails']))

Oh, I missed a parenthesis at the end of line 2 to complete the if().

if(isset($_POST['emails']) && is_array($_POST['emails']))

this works nicely, thank you very much, i owe you one!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.