php - How do I use $_GET["id"] securely with PDO query? -


i'm trying id of page url , use retrieve information database. want ensure id integer length less 4 , redirect parent page if not.

if(isset($_get["id"])) {     $id = (int) $_get["id"];     // if id longer 4 redirect     if(strlen($id) > 4) {         header("location: /parent.php");         exit;     }     try {         $sth = $dbh -> prepare("select id, title, etc, table id = :id");         $sth -> bindparam(':id', $id, pdo::param_int);         $sth -> execute();     } catch(pdoexception $e) {         // print $e -> getmessage();         echo "error";         exit;     }     $feature = $sth -> fetch(pdo::fetch_assoc);     // if query result empty redirect     if($feature == false) {         header("location: /parent.php");         exit;     }     $sth = null; } else { // if id isn't set redirect     header("location: /parent.php");     exit; } 

is way i'm doing secure/correct? i'm still getting grips sort of thing second guessing myself.

also, seems work intended except when id set 123abc (child.php?id=123abc) interprets 123 , still loads information id 123. because i'm casting type ignoring abc part? should concerned still loads , doesn't redirect parent?

you use input filtering instead make sure passed identifier indeed integer; whether it's bigger 9999 shouldn't matter, perhaps testing positive integer idea:

if (($id = filter_input(input_get, 'id', filter_validate_int)) !== false && $id > 0) {     // id passed , it's valid integer } else {     // evil request, die die } 

the use of prepared statements mitigates potential sql injection attack, rest of code doesn't have change, though try make single failure flow instead of 4 separate (but identical) ones.


Comments

Popular posts from this blog

javascript - RequestAnimationFrame not working when exiting fullscreen switching space on Safari -

Python ctypes access violation with const pointer arguments -