Jump to content

Sanitize Checkboxes


JabiRabi

Recommended Posts

Hi, I'm still relatively new to PHP and I'm trying to understand how to sanitize a checkbox within a form.

 

I've done a search through Google, but what I've come across gives short explanations that I don't really understand. 

 

Okay, so here's what I do understand. I can add the values to an array, check the array for the expected values, and what doesn't match those expected values will be sent as a null value. The problem lies in how to implement the array and how to check it. I understand how to sanitize and validate input boxes, that's really no problem. However, checkboxes have me confused.

 

Is there anyone who can help me understand what I'm trying to do? I'm not certain why this is evading me, but it is and I'm wondering if maybe I've overcomplicated the whole thing.

 

Here's what I have so far:

 

 

PHP

<?php
    // Initializing Error Variables To Null.
    $nameError ="";
    $emailError ="";
    $websiteError ="";
    
    $name = $_POST['name'];
    $email = $_POST['email'];
    $website = $_POST['website'];
    $checkboxInput1 = $_POST['checkboxInput1'];
    $checkboxInput2 = $_POST['checkboxInput2'];
    $checkboxInput3 = $_POST['checkboxInput3'];
    $checkboxInput4 = $_POST['checkboxInput4'];
    $checkboxInput5 = $_POST['checkboxInput5'];
    $spamField = $_POST['sField'];
    
    
    $statusMsg = '';
    $msgClass = '';
    
    if(isset($_POST['submit'])){
        if($_POST['name'] != "") {
            
            $_POST['name'] = filter_var($_POST['name'], FILTER_SANITIZE_STRING);
            
            
            if ($_POST['name'] == "") {
                $nameError = "<span class=\"invalid\">Please enter a valid name.</span>";
            }
        } else {
            $nameError = "<span class=\"invalid\">Please enter your name.</span>";
        }
        
        
        if($_POST['email'] != "") {
            
            $_POST['email'] = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);
            
            $_POST['email'] = filter_var($_POST['email'], FILTER_VALIDATE_EMAIL);
            
            if($_POST['email'] == "") {
                $emailError = "<span class=\"invalid\">Please enter a valid email.</span>";
            }
        } else {
            $emailError = "<span class=\"invalid\">Please enter your email.</span>";
        }
        
        
        if($_POST['website'] != "") {
            
            $_POST['website'] = filter_var($_POST['website'], FILTER_SANITIZE_URL);
            
            $_POST['website'] = filter_var($_POST['website'], FILTER_VALIDATE_URL);
            
            if ($_POST['website'] == "") {
                $websiteError = "<span class=\"invalid\">Please enter a valid website start with http:// </span>";
            }
        } else {
            $websiteError = "<span class=\"invalid\">Please enter your website URL.</span>";
        }
        
        
        if($_POST['checkboxInput1'] != "") {
            
            
            
            if ($_POST['checkboxInput1'] == "") {
                
            }
        } else {
            
        }
        
        
        if($_POST['sField'] != "") {
            
            $_POST['sField'] = filter_var($_POST['sField'], FILTER_SANITIZE_STRING);
            
            if ($_POST['sField'] == "") {
                
            }
        } else {
            $sFieldError = "<span class=\"invalid\">Contact Administration</span>";
        }
        
        
        
        
        $toEmail = 'email@email.com';
        $emailSubject = $name.': Contact Request';
        $htmlContent = '<h2>Form Submitted</h2>
            <h4>Name</h4><p>'.$name.'</p>
            <h4>Email</h4><p>'.$email.'</p>
            <h4>Website</h4><p>'.$website.'</p>
            
            
            <h4>Checkbox Input 1</h4><p>'.$checkboxInput1.'</p>
            <h4>Checkbox Input 2</h4><p>'.$checkboxInput2.'</p>
            <h4>Checkbox Input 3</h4><p>'.$checkboxInput3.'</p>
            <h4>Checkbox Input 4?</h4><p>'.$checkboxInput4.'</p>
            <h4>Checkbox Input 5</h4><p>'.$checkboxInput5.'</p>';
        
        // Set content-type header for sending HTML email
        $headers = "MIME-Version: 1.0" . "\r\n";
        $headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
        
        // Additional headers
        $headers .= 'From: '.$name.' <'.$email.'>'. "\r\n";
        
        // Send email
        if(mail($toEmail, $emailSubject, $htmlContent, $headers)){
            $statusMsg = 'Your contact request has been submitted successfully!';
            $msgClass = 'succdiv';
        } else {
            $statusMsg = 'There seems to have been an error with your submission. Contact administration for a resolution.';
            $msgClass = 'errordiv';
        }
    }
?>

 

HTML

<?php if(!empty($statusMsg)){ ?>
    <p class="statusMsg <?php echo !empty($msgClass)?$msgClass:''; ?>">
                        <?php echo $statusMsg; ?>
    </p>
<?php } ?>
<!-- ----     FORM    ---- -->
<form id="form" action="" method="post">
    
    <h2>Form</h2>
    
    
    
    <div>
        <input type="text" id="nameFirst" name="name" /> 
        <label for="nameFirst">
            <span>Name</span>
        </label>
        <span class="hint">
            <p><?php echo $nameError;?></p>
        </span>
    </div>
    
    
    
    <div>
        <input type="email" id="eAddy" name="email" />
        <label for="eAddy">
            <span>Contact Email</span>
        </label>
        <span class="hint">
            <p><?php echo $emailError;?></p>
        </span>
    </div>
    
    
    
    <div>
        <input type="url" id="siteAddress" name="website" />
        <label for="siteAddress">
            <span>Website Address</span>
        </label>
        <span class="hint">
            <p><?php echo $websiteError;?></p>
        </span>
    </div>
    
    
    
    <div>
        <input type="checkbox" id="cbID1"  name="checkboxInput1" class="cbSwitch" />
        <label for="cbID1">Checkbox Input 1</label>
    </div>
    
    
    
    <div>
        <input type="checkbox" id="cbID2"  name="checkboxInput2" class="cbSwitch" />
        <label for="cbID2">Checkbox Input 2</label>
    </div>
    
    
    
    <div>
        <input type="checkbox" id="cbID3"  name="checkboxInput3" class="cbSwitch" />
        <label for="cbID3">Checkbox Input 3</label>
    </div>
    
    
    
    <div>
        <input type="checkbox" id="cbID4"  name="checkboxInput4" class="cbSwitch" />
        <label for="cbID4">Checkbox Input 4</label>
    </div>
    
    
    
    <div>
        <input type="checkbox" id="cbID5" name="checkboxInput5" class="cbSwitch" />
        <label for="cbID5">Checkbox Input 5</label>
    </div>
    
    
    
    <input type="text" id="sField" class="col" name="sField" />
    
    
    <button id="submit" name="submit" type="submit" value="Submit">Submit</button>
    
</form>
Link to comment
Share on other sites

I think you need to be more specific about what you mean by "sanitize". You should absolutely never trust any input from a user. For example, just because your form has a select list with five specific options doesn't mean a user cannot submit a completely different value than what is available in that list. Likewise, checkboxes have assigned values, but a user could very easily change the value submitted.

 

There is, however, one very unique feature about checkboxes that does not apply to other fields. Checkboxe fields are only included in the submitted data if the field is checked (maybe that is the source of your confusion). I notice you are not using "values" for your checkboxes. In some cases you don't have to have them since just identifying that the field name was passed in the POST data is enough to know it was checked. But, you should always have a value as a common practice.

 

So, when it comes to "sanitizing" input, I really see no difference with checkboxes or other fields. Now "how" you sanitize can be different based upon the situation. But, it would be more dependent upon the data type and structure I am receiving vs the field type.

 

In your example above, you are taking a poor approach. When you have a "collection" of checkboxes you should define them as an array. Here is an example using your checkboxes above (note the square brakets in the field name).

<input type="checkbox" id="cbID1"  name="checkboxInputs[]" value="1" class="cbSwitch" />

That will create an array of all the check selections. It will be a numerically based index starting at zero. You could also specify the index for each field.  The index can be a number or text, but do not put quotes around the index as you would in PHP code. Example:

<input type="checkbox" id="cbID1"  name="checkboxInputs[One]" value="1" class="cbSwitch" />

But, I would go with the first option for your code. It all depends on what your use is.

 

 

OK, so onto your processing page. You may want to verify that the user has selected at least one of the checkboxes. If so, you might do the following

if(isset($_POST['checkboxInputs'])
{
    //Error condition
}
else
{
    //Do something with the data
}

If you need more validations then add them. In many cases you can use array_filter() with other PHP functions to remove values that are invalid. In some cases you may use the values in a query (using prepared statements) to filter out invalid values. There are many different scenarios and I can't provide examples of each.

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.