开发者

Using php to post checkbox selections in email

I'm brand new to php so struggling to figure this one out from existing answers.

I need to see which of up to 4 checkboxes have been selected on a form in the resulting notification email.

The form IS sending the email, but it only includes the sender's comments, NOT the checkbox selection(s) made.

Anyone willing to point out the error in my code? Please go ahead and assume the lowest comprehension level of n00bness.

Here's the relevant form html:

    <input type="checkbox" name="timeslots[]" value="thu" />Thursday after 7pm <br/>
开发者_JAVA百科    <input type="checkbox" name="timeslots[]" value="fri" />Friday after 5.30pm <br/>
    <input type="checkbox" name="timeslots[]" value="sat" />Saturday afternoon<br/>
    <input type="checkbox" name="timeslots[]" value="sun" />Sunday afternoon<br/>

..and here's the php script I've cobbled together so far:

<?php
$email_to = "me@mysite.com";
$name = $_POST["name"];
$email = $_POST["email"];
$comments = $_POST["comments"];
$email_from = $_POST["email"];
$email_subject = "Form request";
$times = $_REQUEST["timeslots"];

if(!filter_var($email_from, FILTER_VALIDATE_EMAIL)) {
    // Invalid email address
    die("The email address entered is invalid.");
}


$headers =
"From: $email_from .\n";
"Reply-To: $email_from .\n";

$body = "Name: $name\n  Message: $comments\n 
  $times";

ini_set("sendmail_from",$email_from);
$sent=mail($email_to,$email_subject,$comments,$headers,"-f".$email_from);
if($sent)
{
header("Location:thanks.html");
}else{
header("Location:senderror.html");
}
?>


The problem is that $times is an array. you should do:

$times = $_POST["timeslots"];

$times = implode(', ', $times);

and then you can use it in your email

$times is an array because in PHP when you declare input elements with an array as name (like you did), an array is posted. In your case only the selected checkboxes will be posted.

One more thing: only the value of the checkbox will be posted, so if you check the first two checkboxes you will send "thu, fri" in the mail.


$times is array in your code:

<?php
$email_to = "me@mysite.com";
$name = $_POST["name"];
$email = $_POST["email"];
$comments = $_POST["comments"];
$email_from = $_POST["email"];
$email_subject = "Form request";
$times = $_POST["timeslots"];

if(!filter_var($email_from, FILTER_VALIDATE_EMAIL)) {
    // Invalid email address
    die("The email address entered is invalid.");
}

$strTimes = implode(", ", $times);

$headers[] = "From: $email_from .\n";
$headers[] = "Reply-To: $email_from .\n";

$body = "Name: $name\n  Message: $comments\n $strTimes";

ini_set("sendmail_from",$email_from);
$sent=mail($email_to,$email_subject,$comments,$headers,"-f".$email_from);
if($sent)
{
header("Location:thanks.html");
}else{
header("Location:senderror.html");
}
?>

Edited: in your original code line 17 & 18 should be arrays, (line 18 in your original code is unused)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜