Sanitising a POST array for INSERT query
Morning SO,
I have a checkbox array (name = "cat[]") in a form which at present, contains six values, 1- 6 (it may contain more in the future). A user can select any number of these.
These values are then collected in:
$_SESSION['cat'] = $_POST['cat'];
(They're in a session because there's a step or two before the actual insert query)
What i want to do is Sanitise them. I have tried
$_SESSION['cat'] = (int)$_POST['cat'];
But that seems to strip all values from it.
Can someone help with the appropriate 开发者_高级运维method of sanitising this for safe insertion into a database?
Thanks in advance, as always, Dan
Simple solution
$values = array_map('intval',$_POST['cat']);
But that will result in all non-integer values replaced by 0, rather than removing it.
Much better solution is using prepared statments (I'm tired to tell it in each post about mysql insert... :) ), like this:
$stmt = $pdo->prepare("*your query with params replaced with ?*");
foreach ($_POST['cat'] as $cat){
//check that $cat is integer.
if ($cat === 0 || (!empty(intval($cat)))
$stmt->execute(array($cat));
}
This way you'll have double protection: you check for int yorself and PDO
properly uses it in sql statement.
What Kind of values does $_POST['cat']
have? I'm assuming you want it to be an integer, but if it's not, it will spit out zero when casted to an int
.
Make sure your value=""
in your HTML actually contains integers. I can't say much more without the checkbox HTML.
You can use mysql_real_escape_string
to make sure the string doesn't generator SQL errors and then the php intval
function to make sure to get an integer value from the string.
PHP:
if ($_POST['submit']) {
foreach ($_POST['cat'] as $key => $value) {
$_SESSION['cat'][] = intval(mysql_real_escape_string($value));
}
}
if (isset($_SESSION['cat'])) {
foreach($_SESSION['cat'] as $cat) {
echo "Cat: $cat<br />";
}
}
HTML:
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
1 <input name="cat[]" type="checkbox" value="1" /><br />
2 <input name="cat[]" type="checkbox" value="2" /><br />
3 <input name="cat[]" type="checkbox" value="3" /><br />
<input type="submit" value="submit" name="submit" />
</form>
If with safe you mean all as integer:
foreach ($_POST['cat'] as $key => $value) {
$_SESSION['cat'][] = int()$value;
}
Else, you could replace the int()$value
with mysql_real_escape_string($value)
.
Fixed typo
精彩评论