Hi all,

I'm working with a PHP mail form and so far all is working well. It is returning everything from the form except the checkbox results. For them, it just says 'array'. I've searched high and low for a fix but I can't seem to get it working using the solutions I have found online. Part of the issue is that I'm not 100% sure 'where' in the mail form to put the code. My PHP mail form is as follows:

// OPTIONS - PLEASE CONFIGURE THESE BEFORE USE!

    $yourEmail = "myemailhere@myemail.com"; // the email address you wish to receive these mails through
    $yourWebsite = "My Website name"; // the name of your website
    $thanksPage = 'thanks.php'; // URL to 'thanks for sending mail' page; leave empty to keep message on the same page 
    $maxPoints = 4; // max points a person can hit before it refuses to submit - recommend 4


// --- DO NOT EDIT BELOW HERE -----------------------

$error_msg = null;
$result = null;

function isBot() {
    $bots = array("Indy", "Blaiz", "Java", "libwww-perl", "Python", "OutfoxBot", "User-Agent", "PycURL", "AlphaServer", "T8Abot", "Syntryx", "WinHttp", "WebBandit", "nicebot");

    $isBot = false;
    foreach ($bots as $bot)
    if (strpos($_SERVER['HTTP_USER_AGENT'], $bot) !== false)
        $isBot = true;

    if (empty($_SERVER['HTTP_USER_AGENT']) || $_SERVER['HTTP_USER_AGENT'] == " ")
        $isBot = true;

    exit("Bots not allowed.</p>");
}

if ($_SERVER['REQUEST_METHOD'] == "POST") {
    function clean($data) {
        $data = trim(stripslashes(strip_tags($data)));
        return $data;
    }

    $points = (int)0;

    $badwords = array("adult", "beastial", "bestial", "blowjob", "clit", "cum", "cunilingus", "cunillingus", "cunnilingus", "cunt", "ejaculate", "fag", "felatio", "fellatio", "fuck", "fuk", "fuks", "gangbang", "gangbanged", "gangbangs", "hotsex", "hardcode", "jism", "jiz", "orgasim", "orgasims", "orgasm", "orgasms", "phonesex", "phuk", "phuq", "porn", "pussies", "pussy", "spunk", "xxx", "viagra", "phentermine", "tramadol", "adipex", "advai", "alprazolam", "ambien", "ambian", "amoxicillin", "antivert", "blackjack", "backgammon", "texas", "holdem", "poker", "carisoprodol", "ciara", "ciprofloxacin", "debt", "dating", "porn", "link=", "voyeur");
    $exploits = array("content-type", "bcc:", "cc:", "document.cookie", "onclick", "onload", "javascript");

    foreach ($badwords as $word)
        if (strpos($_POST['message'], $word) !== false)
            $points += 2;

    foreach ($exploits as $exploit)
        if (strpos($_POST['message'], $exploit) !== false)
            $points += 2;

    if (strpos($_POST['message'], "http://") !== false || strpos($_POST['message'], "www.") !== false)
        $points += 2;
    if (isset($_POST['nojs']))
        $points += 1;
    if (preg_match("/(<.*>)/i", $_POST['message']))
        $points += 2;
    if (strlen($_POST['name']) < 3)
        $points += 1;
    if (strlen($_POST['message']) < 15 || strlen($_POST['message'] > 1500))
        $points += 2;

    foreach ($_POST as $key => $value)
        $_POST[$key] = trim($value);

    if (empty($_POST['name']) || empty($_POST['email']) || empty($_POST['message'])) {
        $error_msg .= "Name, e-mail and comments are required fields. \n";
    } elseif (strlen($_POST['name']) > 15) {
        $error_msg .= "The name field is limited at 15 characters. Your first name or nickname will do! \n";
    } elseif (!preg_match("/^[a-zA-Z-'\s]*$/", stripslashes($_POST['name']))) {
        $error_msg .= "The name field must not contain special characters. \n";
    } elseif (!preg_match('/^([a-z0-9])(([-a-z0-9._])*([a-z0-9]))*\@([a-z0-9])(([a-z0-9-])*([a-z0-9]))+' . '(\.([a-z0-9])([-a-z0-9_-])?([a-z0-9])+)+$/i', strtolower($_POST['email']))) {
        $error_msg .= "That is not a valid e-mail address. \n";
    } elseif (!empty($_POST['url']) && !preg_match('/^(http|https):\/\/(([A-Z0-9][A-Z0-9_-]*)(\.[A-Z0-9][A-Z0-9_-]*)+)(:(\d+))?\/?/i', $_POST['url']))
        $error_msg .= "Invalid website url.";

    if ($error_msg == NULL && $points <= $maxPoints) {
        $subject = "Desktop Support Form Email";

        $message = "You received this e-mail message through your website: \n\n";
        foreach ($_POST as $key => $val) {
            $message .= ucwords($key) . ": " . clean($val) . "\r\n";
        }
        $message .= 'IP: '.$_SERVER['REMOTE_ADDR']."\r\n";
        //$message .= 'Browser: '.$_SERVER['HTTP_USER_AGENT']."\r\n";
        //$message .= 'Points: '.$points;

        if (strstr($_SERVER['SERVER_SOFTWARE'], "Win")) {
            $headers   = "From: $yourEmail \r\n";
            $headers  .= "Reply-To: {$_POST['email']}";
        } else {
            $headers   = "From: $yourWebsite <$yourEmail> \r\n";
            $headers  .= "Reply-To: {$_POST['email']}";
        }

        if (mail($yourEmail,$subject,$message,$headers)) {
            if (!empty($thanksPage)) {
                header("Location: $thanksPage");
                exit;
            } else {
                $result = 'Your mail was successfully sent.';
            }
        } else {
            $error_msg = 'Your mail could not be sent this time.';
        }
    } else {
        if (empty($error_msg))
            $error_msg = 'Your mail looks too much like spam, and could not be sent this time. ['.$points.']';
    }
}
function get_data($var) {
    if (isset($_POST[$var]))
        echo htmlspecialchars($_POST[$var]);
}

My HTML is stndard form fare. I have assigned 'name="feedback[]"' to the checkboxes as I had found that naming them the same and using the square brackets facilitates the passing of the checkbox information. I just dont know how to enter it into my mail form above. Thanks in advance for any help you can give.

it's your html

<input type="checkbox" name="feedback" value="1"> 1 
<input type="checkbox" name="feedback" value="2"> 2 
<input type="checkbox" name="feedback" value="3"> 3 
<input type="checkbox" name="feedback" value="4"> 4 
<input type="checkbox" name="feedback" value="5"> 5

in php put this code

if($_POST["feedback"] == '1' ) { some data  }
else if($_POST["feedback"] == '2' ) { some data  }
else if($_POST["feedback"] == '3' ) { some data  }
else if($_POST["feedback"] == '4' ) { some data  }
else { some data }

if checkbox 2 is selected than 2 will be pass as value of feedback as post parameter. ( feedback=2 )

may be this will be helpful.

The display of "Array" is a clue as to what is actually happening here:

 76. foreach ($_POST as $key => $val) {
 77.    $message .= ucwords($key) . ": " . clean($val) . "\r\n";
 78. }

The loop here loops through all the form elements and adds them to the email. Problem is it expects text values, and a checkbox element submits an array(because it potentially has multiple values). What you have to do is add an if statement that checks if $val is an array and loops through it. For instance:

foreach ($_POST as $key => $val) {
    $message .= ucwords($key) . ": ";
    if(is_array($val)) {
        foreach($val as $subVal) {
            echo $subVal . ", ";
        }
    }
    else {
        echo clean($val);
    }
    echo "\r\n";
}

Thanks for your help Lsmjudoka. I'm very new to all this so not 100% sure about it. Are you saying that I replace wth first block of code with the one you posted? i just wasnt sure where to enter it into the file. Thanks again!

Member Avatar for diafol

You don't show your form markup so it's difficult to know what you're passing. Assuming...

<input type="checkbox" name="mycheck[]" value="1" />
<input type="checkbox" name="mycheck[]" value="2" />
<input type="checkbox" name="mycheck[]" value="3" />
<input type="checkbox" name="mycheck[]" value="4" />
<input type="checkbox" name="mycheck[]" value="5" />

And you want each checked checkbox to include a string, then in your formhandling code...

$outputString = '';
if(isset($_POST['mycheck']))
{
    $output = array();
    $checks = (array) $_POST['mycheck'];
    $checkStrings = array(1=>"Do this","Do that","Do something else",...);
    foreach($checks as $value)
    {
        $output[] = $checkStrings[$value];
    }
    $outputString = implode("<br />", $output);
}

Possibly something like that. Alternatively, it may be that your checkboxes are not linked and that you don't have array names, then you'd need to test for each one individually.

Keeping them checked on return to form is a bit trickier... for that you could actually set your indexes...

<input type="checkbox" name="mycheck[0]" />
<input type="checkbox" name="mycheck[1]" />
<input type="checkbox" name="mycheck[2]" />
<input type="checkbox" name="mycheck[3]" />
<input type="checkbox" name="mycheck[4]" />

Then...

$outputString = '';
$returnChecks = array();
if(isset($_POST['mycheck']))
{
    $output = array();
    $checks = (array) $_POST['mycheck'];
    $checkStrings = array("Do this","Do that","Do something else",...);
    foreach($checks as $key=>$value)
    {
        $output[] = $checkStrings[$key];
        $returnChecks[] = $key;
    }
    $outputString = implode("<br />", $output);
}

That may be a far better method anyway. $returnChecks can be passed back to the form (if required).

Yeah, you would want to replace the first loop with the second 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.