I have a form that submits to codeigniter email class and sends emails to my clients. I have a simple to
input field.
<input type="text" name="to" class="form-control">
I want to be able to type multiple email addresses into this one field and send emails to them all at once. This is pretty simple in codeigniter I just need to get the emails into an array and placed in the to
param in codeigniter.
So I want to be able to type something like the below into the field, submit it, break the post data into an array with the breaking point being ,
or a comma.
someone@me.com, yournamehere@example.com, myself@myowndomain.com
The above would need to go into an array such as this:
$list = array(
'someone@me.com',
'yournamehere@example.com',
'myself@myowndomain.com,
);
My real question is, what is the fastest and cleanest way to break the regular post data from the input field to
into an array by using ,
a comma as the breaking point.
Use PHP explode() function. More decent manual in the PHP documentation. This is the idea but if you gonna receive these emails separated by comma in the backend, you should use $_GET or $_POST.
<?php
//$str = $_POST['emails'];
$str = "someone@me.com, yournamehere@example.com, myself@myowndomain.com";
print_r (explode(",",$str));
?>
Syntax: explode(separator,string,limit). In your case you want comma to be the separator so that's why the separator should be comma.
Give this a go; it worked fine for me, while adding preg_replace()
to remove all whitespace.
Plus, there is also a second method using a filtered method to help protect against XSS injection using PHP's FILTER_VALIDATE_EMAIL
filter.
<?php
if(isset($_POST['submit'])){
$to = $_POST['to'];
$var = explode(',', $to);
$me = "you@example.com";
foreach($var as $mailto){
$mailto = preg_replace('/\s+/', '', $mailto); // remove all whitespace
$subject = 'Message subject ' . $name; // optional variable
$message = "Hello there.";
$headers = "From: {$me}
";
$headers .= "Reply-To: {$mailto}
";
mail($mailto, $subject, $message, $headers);
}
} // brace for isset
?>
<form action="" method="post">
<input type="text" name="to" class="form-control">
<input type="submit" name="submit" value="Send">
</form>
Using a filtered method using PHP's FILTER_VALIDATE_EMAIL
filter.
<?php
if(isset($_POST['submit'])){
$to = $_POST['to'];
$me = "you@example.com";
$to = preg_replace('/\s+/', '', $to);
foreach(explode(",", $to) as $mailto){
if(!filter_var($mailto, FILTER_VALIDATE_EMAIL))
{ die("Sorry."); }
else{
$subject = 'Message subject from ' . $name; // optional variable
$message = "Hello there.";
$headers = "From: {$me}
";
$headers .= "Reply-To: {$mailto}
";
if(mail($mailto, $subject, $message, $headers)){
echo "Mail sent to $mailto ";
}
}
}
} // brace for isset
?>
<form action="" method="post">
<input type="text" name="to" class="form-control">
<input type="submit" name="submit" value="Send">
</form>