pdo - php pagination security regarding INT -
i'm looking update pagination on page pdo. however, want make sure 100% free sql injection etc.
below content of pagination script have found think work without issues. pulling data url i'm bit concerned regarding line:
if (isset($_get["page"])) { $page = $_get["page"]; } else { $page=1; };
i can see isset there check if variable null (i think) can't see checks if not number.
i thinking of changing to:
if (isset($_get["page"])) { $page = (int)$_get["page"]; } else { $page=1; };
as think check if page variable number. or should be:
if (isset((int)$_get["page"])) { $page = $_get["page"]; } else { $page=1; };
or use int on both? think in old mysql have used striptags etc not sure pdo (still learning).
here full code before change mentioned above.
<?php include('connect.php'); if (isset($_get["page"])) { $page = $_get["page"]; } else { $page=1; }; $start_from = ($page-1) * 3; $result = $db->prepare("select * members order id asc limit $start_from, 3"); $result->execute(); for($i=0; $row = $result->fetch(); $i++){ ?> <tr class="record"> <td><?php echo $row['a']; ?></td> <td><?php echo $row['b']; ?></td> <td><?php echo $row['c']; ?></td> </tr> <?php } ?> </tbody> </table> <div id="pagination"> <?php $result = $db->prepare("select count(id) members"); $result->execute(); $row = $result->fetch(); $total_records = $row[0]; $total_pages = ceil($total_records / 3); ($i=1; $i<=$total_pages; $i++) { echo "<a href='index.php?page=".$i."'"; if($page==$i) { echo "id=active"; } echo ">"; echo "".$i."</a> "; }; ?>
connect.php contains
$db = new pdo('mysql:host='.$db_host.';dbname='.$db_database, $db_user, $db_pass); $db->setattribute(pdo::attr_errmode, pdo::errmode_exception);
any or guidance appreciated. if can spot else security wise, please let me know.
edits:
added line:
$db->setattribute(pdo::attr_emulate_prepares, false);
to connect.php
any other security tips?
use parameterized queries avoid possibility of injections. using pdo can
- pass user provided values execute in array
- place question mark placeholder in place of user data
$result = $db->prepare("select * members order id asc limit ?, 3"); $result->execute(array((int)$start_from));
you can bind it, http://php.net/manual/en/pdostatement.bindparam.php (based on doc , other threads, don't bind).
$result = $db->prepare("select * members order id asc limit :start, 3"); $result->bindparam(':start', (int)$start_from, pdo::param_int); $result->execute();
here's longer thread on it, how can prevent sql injection in php?
also php notes on it, http://php.net/manual/en/pdo.prepared-statements.php
for longer sample, if had multiple values coming in:
$result = $db->prepare("select * members username = ? , email = ? order id asc limit ?, 3"); $result->execute(array($_get['name'], $_get['email'], $start_from));
Comments
Post a Comment