4

I'm using PDO, and my $_POST['arraywithdata'] is an array filed with numeric values. I think that this is not enough secure, I just wan't to be sure and prevent myself from a hack.

This is my code:

$arr = $_POST['arraywithdata'];
$SQL->query("UPDATE `data_s` SET `set` = 1 WHERE `id` IN " . implode(", ", $arr));

As you can see, I'm not checking if the post code in a int or something.

Should I rather use something like:

implode(", ", (int) $arr)

?

I guess the above will not work, since array can not be an integer.

Cyclone
  • 14,839
  • 23
  • 82
  • 114
  • Good point - this is indeed not secure. I think you'll need to walk through each value individually and make sure it's an int, or escape them. `(int)$arr` will not work - it will break the array. – Pekka Oct 13 '11 at 15:54
  • You might try using placeholders to do this. – jprofitt Oct 13 '11 at 15:55
  • Note that the [`IN` operator](http://dev.mysql.com/doc/refman/5.5/en/comparison-operators.html#function_in) requires parentheses. – Gumbo Oct 13 '11 at 16:04

3 Answers3

14

You need to convert each value of the array and not the array itself. You can use array_map to do so:

implode(", ", array_map('intval', $arr))

Here array_map will apply intval to each value of $arr and return a new array with the return values.

But as you’re using PDO, you might also be interested in a PDO solution.

Community
  • 1
  • 1
Gumbo
  • 643,351
  • 109
  • 780
  • 844
0

Recently, i faced this problem Here is what i did Hope this help

$arr = array(20,40,50);
$query[] = "UPDATE `data_s` SET `set` = 1 WHERE `id` IN (";
$count = count($arr);
foreach($arr as $v)
{
   $query[] = (int)$v;
   if ($count > 1)
    {
      $sql[] =",";
    }
   $count--;
}

$query[] = ")";
$query = implode("\n", $query);

$SQL->query($query);

IT will give you query like this "UPDATEdata_sSETset= 1 WHEREidIN (20,40,50)";

Harry
  • 44
  • 6
0

It sounds like a bit of a messy way to pass an array to your script, if I were you I'd do the following:

<input name="test[]" value="arrayitem1" type="text" />
<input name="test[]" value="arrayitem2" type="text" />

Then in the PHP you can either loop through the data using a foreach look and checking is_int or use array_map with intval and then explode the data.

Prisoner
  • 27,391
  • 11
  • 73
  • 102