Jump to content

Passing checkbox values to the mail function


fwolf

Recommended Posts

Hi everyone,

I'm trying to pass checkbox values to the PHP mail function. I've setup XAMPP and got the mail function to work before. Here is my html code below:

 <body>
            <div class="container">
            <!-- Feedback Form Starts Here -->
            <div id="feedback">
            <!-- Heading Of The Form -->
            <div class="head">
            
            </div>

            <!-- Feedback Form -->
              
            <form action="secure_email_code.php" class="form-design col-md-4" method="post" name="form">

            <h1>What's Your CO<span class="subscript">2</span> Emission?</h1>
                <input name="vname0" placeholder="Your First Name" type="text" value=""><br>
                <input name="vname1" placeholder="Your Last Name" type="text" value=""><br>
                <input name="vemail" placeholder="Your Email" type="text" value=""><br>
                <!--input name="sub" placeholder="Subject" type="text" value=""><br-->
                <!--<textarea name="msg" placeholder="Type your text here..."></textarea><br>-->

                
            
            <h2 >Questions</h2><br>

            
                <label>Fast Food?</label>
                <input type="checkbox" value="1" name="cbox[]"><br>
            
                <label>Home Made?</label>
                <input type="checkbox" value="2" name="cbox[] "><br>
            
                
                <input id="send" name="submit" type="submit" value="Send Feedback"><br>

            </form>

        
            </div>
            <!-- Feedback Form Ends Here -->
            </div>
        </body>

My PHP code is echoing the results. Except for the mail function. Now, here is my php code below:

 

<?php

if(isset($_POST["submit"])){
     //Checking For Blank Fields..conditional
    if($_POST["vname0"]==""||$_POST["vname1"]==""||$_POST["vemail"]==""|| (empty($_POST['cbox']) ) ){
    echo "<h1>Fill All Fields..</h1>";
    }


    else{
        // Check if the "Sender's Email" input field is filled out
        $email=$_POST['vemail'];
        $name0=$_POST['vname0'];
        $name1=$_POST['vname1'];
        $name= array($name0, $name1);
        // Sanitize E-mail Address
        $email =filter_var($email, FILTER_SANITIZE_EMAIL);
        // Validate E-mail Address
        $email= filter_var($email, FILTER_VALIDATE_EMAIL);
            if (!$email){
            echo "Invalid Sender's Email";
            }

            //$subject = $_POST['sub'];

                    //for (init counter; test counter; increment counter) {
                    //  code to be executed for each iteration;
                    //}

                    // init counter: Initialize the loop counter value
                    // test counter: Evaluated for each loop iteration. If it evaluates to TRUE, the loop continues. If it evaluates to FALSE, the loop ends.
                    //increment counter: Increases the loop counter value
                    //foreach($_POST['check'] as $value) {
                    // $check_msg .= "Checked: $value\n";
                        //}

        foreach($_POST['cbox'] as $value){
            if($value == 1){
                $value = 
                "
                <h2>Fast Food</h2>
                <p>The stuff that kills.</p>
                ";

                echo " $name[0] selected: $value\n ";  
            } elseif ($value == 2) {
                $value = 
                "
                <h2>Home Made</h2>
                <p>Yum! There is nothing like a home cooked meal!</p>
                ";

               echo " $name[0] selected: $value\n ";    
            }
            $body = "CFP Results\r\n From: $name[0] $name[1]\r\n, Email: $email\r\n, Results: $value\r\n";
           
            
        }

        $to = "franklin120889@gmail.com";
        mail($to, "CFP_DATA", $body, $email);
        
            


                
                //$message = wordwrap($message, 70);


                // Send Mail By PHP Mail Function
                
                

        }
    }
    
?>

 

Link to comment
Share on other sites

Just FYI, use empty for all your checks

if (empty($_POST["vname0"]) || empty($_POST["vname1"]) || empty($_POST["vemail"]) || empty($_POST['cbox'])) {
    echo "<h1>Fill All Fields..</h1>";
}

However, this is unsophisticated, because a single space entered will pass the test.  PHP has validators that can be used with filter_var for things like email that can provide some better hygiene, but at very least you should have a function that trims entry of your text fields.

Better:

if (empty(trim($_POST["vname0"])) || empty(trim($_POST["vname1"])) || empty(trim($_POST["vemail"])) || empty($_POST['cbox'])) {
    echo "<h1>Fill All Fields..</h1>";
}

 

Link to comment
Share on other sites

5 hours ago, fwolf said:

I'm trying to get the mail function to work

you always need error handling for statements that can fail. you should also insure that you have php's error_reporting set to E_ALL and display_errors set to ON, in the php.ini on your development system, so that php will help you by reporting and displaying all the errors it detects. if you run this code on a live/public server, you would instead set display_errors to OFF and set log_errors to ON.

the mail() function returns either a true or a false value. for a false value, php will either display or log the actual error information, so that you will have an indication of the call failing. however, in your code for a false value, you should log your own information consisting of the datetime, the php error that occurred, and the parameter values that were supplied to the mail() call. this will let you debug problems that are occurring due to things like email addresses that cause an error. for a true value, because email can be unreliable, you should actually log or insert rows in a database table with the same information, so that you can check if you are receiving all the emails that are being sent.

once you do the above you will probably get errors about an invalid mail header, a missing From: header, and/or errors about relaying restrictions.

the mail headers must contain a From: email address. the syntax is From: email address \r\n this email address is NOT the address that was entered in your form. these emails are not being sent from the user's email address (except perhaps during testing that you may have done using an email address that does correspond to your web hosting.) they are being sent from the mail server at your web hosting. the email address in the From: header must correspond to your web hosting. you can put the entered email address into a Reply-to: mail header.

the are a number of issues with the posted code. the most immediate problems are -

  1. the code is not indented properly, so you cannot see what exactly it is or is not doing. the current code will attempt to sent the email, even if the entered email address is not valid. you should actually store the user/validation errors in an array, using the field name as the array index. then, after the end of all the validation logic, if the array is empty, use the submitted data. this will simplify all the nested conditional logic. to display the errors, at the appropriate location in the html document, you would test if the array is not empty, then either loop over or implode the contents of the array to display the error messages.
  2. the $body variable is being reassigned on each pass through the foreach(){} loop. this leaves you with only the last checkbox message as part of the body. since there could be any number of checkbox messages, i recommend that you  add each one to an array, inside of the loop, then after the end of the loop, implode them with whatever markup you want between them, then append this to the end of the main message body.
  3. don't write out code for each possible value. if you had 10 checkboxes, would writing out all that conditional logic 10X make sense? you should use a data-driven design, where you have a data structure (array or database table) that holds the definition of the data. for the checkboxes, you would have an entry in the defining array for each checkbox. the main array index would be the values (1,2,...) each entry in the main array would be an array with elements for the label, and the mail body text. you would use this defining data structure when dynamically building the checkbox markup, when validating the submitted checkbox values, and when adding the text to the mail body.

 

  • Like 1
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.