Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

PHP

Issues with form validation regarding an array in $_POST and the stripos() function. Is my solution correct?

I am creating an online registration form which sends user inputs to an administrator via email.

I have used quite a few checkboxes, all being sent to an array called "programmes" within $_POST by changing checkbox input name attributes to "programmes[]".

I have also implemented the following code, from the Building a simple PHP application, to prevent form injection by spammer bots

foreach($_POST as $value) {
if (stripos($value, 'Content-Type:') !== FALSE ) {
    echo "Invalid submission";
    exit();
}

After this however, every form submission would direct to the "Invalid Submission" text on an empty page. After reading a bit about the stripos() function I think I understood that its first argument is where it searches for a string value, and the second argument is the string value it searches for.

Based on this understanding I figured it was probably the array() that was preventing the code from executing properly.

So I decided to change the above block to this:

        foreach($_POST as $value) {
            // If malicious inputs are detected, exit code.

            // Checks if value is array first to run validation on its elements.
            if (gettype($value) == "array") {
                // Checks if there are elements in the array
                if(count($value) > 0) {
                    foreach($value as $element) {
                        if (stripos($element, 'Content-Type:') !== FALSE) {
                            echo "Invalid submission";
                            exit();
                        }
                    }
                }
            }
            // If value is not an array, use the check below
            elseif (stripos($value, 'Content-Type:') !== FALSE ) {
                echo "Invalid submission";
                exit();
            }
        }

This seems to have solved the problem. Have I understood this procedure correctly or did I possibly leave some kind of vulnerability loophole?