views:

173

answers:

1

For some reason my checkbox array values don't show up in $_POST.

For example:

<form method="post" action="">
    <input type="checkbox" name="cb[]" value="1">
    <input type="checkbox" name="cb[]" checked="checked" value="2">
    <input type="checkbox" name="cb[]" value="3">
    <input type="checkbox" name="cb[]" checked="checked" value="4">
    <input type="checkbox" name="cb[]" checked="checked" value="5">
    <input type="checkbox" name="cb[]" value="6">
    ...
    <input type="checkbox" name="cb[]" checked="checked" value="26">
    <input type="checkbox" name="cb[]" value="27">
    <input type="submit" value="insanitizer"/>
</form>

When submit:

<?php
print_r($_POST); //Because print_r($_POST['cb']); gives ''

Array (
   [category] =>
)

print_r($_REQUEST['cb']);  //Showing the correct array name was used

Array
(
    [0] => 2
    [1] => 4
    [2] => 5
    [3] => 26
)
?>

I'm happy that I can at least get the checkbox data here, but I'm left with one question:

Wtf?

+1  A: 

DUMBASS

As part of general initialization I run $_POST and $_GET through:

<?php
if(sizeof($_POST) > 0){
    foreach($_POST as $key => $value){
        $_POST[$key] = $this->_db->realEscapeString($value);
    }
}
if(sizeof($_GET) > 0){
    foreach($_GET as $key => $value){
        $_GET[$key] = $this->_db->realEscapeString($value);
    }
} 
?>

Which seems to nuke any arrays...

Replaced above with:

<?php
...
if(sizeof($_GET) > 0){
        $this->initDbCleanArray($_GET);
    }
}
...

private function initDbCleanArray($a)
{
    if(sizeof($a) > 0){
        foreach($a as $key => $value){
            if(is_array($a[$key])){
                $this->initDbCleanArray($a[$key]);
            }
            else{
                $a[$key] = $this->_db->realEscapeString($value);
            }
        }
    }
}
?>

realEscapeString = mysql_real_escape_string

...and $_POST['cb'] lives!

Michael Robinson
They *shouldn't* nuke your arrays.
quantumSoup
Be that as it may, they did? I commented the above code out, and walaa, cb array appears in $_POST...
Michael Robinson
Best practice is to escape your strings immediately before they are inserted into the database, and not before. Prevents stuff like this from happening.
Scott Saunders
I can see how that is best practice. I thought I'd escape it all right at the start to prevent a 'forgot to escape db strings' catastrophe...
Michael Robinson
@Scott Saunders I spent the last day refactoring my code to use PDO in my DB wrapper instead of the crap I inherited. Much better, no more shotgun escaping :)
Michael Robinson