php - Is $_SESSION safe from sql injects? -
i use pdo access mysql database, , want use in. sadly don't seam work prepare, wrote function
function is_numeric_array($array){ if(!is_array($array)) return is_numeric($array); if(is_array($array)) foreach($array $int) if(!is_numeric($int)) return false; return true; }
then used this
if(!is_numeric_array($_session['story'])){ die("error, array contains non-integers"); } $query = "("; for($i = 0; $i<count($_session['story']); $i++) $query .= $_session['story'][$i].(count($_session['story'])-1 != $i ? "," : ""); $query .= ")"; //collect data needed $stories = openconnection() -> query("select * `stories` `id` in {$query}") -> fetchall();
i know it, looks ugly. don't want sql injects.
you don't have test input being numeric, because in mysql, string e.g. '123abc'
in numeric context (like being compared integer column id
) implicitly takes digits , ignores rest. non-numeric string 'abc'
has integer value 0 because there no leading digits.
the point is, values safe sql injection if use query parameters. whether inputs come $_session or source irrelevant. $_session neither safe or unsafe respect sql injection, it's how pass data query matters.
i simplify code format list of parameter placeholders:
$placeholders = implode(',', array_fill(1, count((array)$_session['story']), '?'));
and forget bindparam(), pass array execute()
.
//collect data needed $storyquery = openconnection() -> prepare("select * `stories` `id` in ({$placeholders})"); $storyquery -> execute((array)$_session['story']); $story = $storyquery -> fetchall();
re comment:
in pdo, can use either named parameters :id
, or can use positional parameters, ?
(but don't mix these 2 types in given query, use 1 or other).
passing array execute()
automatically binds array elements parameters. simple array (i.e. indexed integers) easy bind positional parameters.
if use named parameters, must pass associative array keys of array match parameter names. array keys may optionally prefixed :
it's not required.
if you're new pdo, pays read documentation. there code examples , everything!
Comments
Post a Comment