防止GET变量的错误输入


Preventing bad input from GET variable

我有一个变量,它从URL获取值。

if (isset($_GET['page'])) {
    $getPage = $_GET['page'];
} else {
    $getPage = "";
}
if ($getPage == "" || $getPage == "1") {
    $page = 0;
} else {
    $page = ($getPage * 6) - 6;
}

在它得到这个值之后,它向数据库发送一个查询,请求信息。我如何确保输入是数字并且不超过可用的数量?

下面是查询:

$query = "SELECT * FROM dbname LIMIT $page,6 ";
$select_all_list_items = mysqli_query($connection, $query);

现在,如果我手动更改url并输入一个超过页面数的数字,它不会显示任何内容,或者如果我在那里输入字母,它会显示一个错误。在这两种情况下,我都希望将用户重定向到第一页。

检查数字输入和无效页码,

$pageCount = $totalRecords / $recordsPerPage;
/* where $totalRecords is count of total records from db and $recordsPerPage is total rows per page */
if(!is_numeric($_GET['page']) || $_GET['page']>$pageCount){
    $getPage = "1";
}

首先需要从数据库中检索总页面:

$countQuery = 'SELECT COUNT(*) FROM dbname';
$countResult = mysqli_query($connection, $countQuery);
$countResultRow = mysqli_fetch_row($countResult);
$numPages = intval($countResultRow[0]);

然后你需要实现一些检查你的get变量:

if ($numPages < 0) {
    throw new Exception('No pages to show!');
}
if (!is_numeric($getPage)) {
    $getPage = 1;
}
if ($getPage > $numPages) {
    $getPage = 1;
}
if ($getPage < 1) { 
    $getPage = 1;
}

小心将GET值直接传递到SQL查询中,这是一个安全风险,因为它可能导致通过URL操纵数据库。阅读SQL注入,了解更多关于"转义"数据预查询的信息。

像这样的东西

 $page = 1;  //default page 1
 if(isset($_GET['page']) && preg_match('/[a-z]/i', $_GET['page'])){
    // if set and alpha
    header('Location: url of first page');
    exit;
 }else{
    //not sure of this part but ( that's what the OP has so i'll go with it )
    $page = ( $_GET['page'] * 6 ) - 6;  ///could be 0 on page 1 6*1-6, just saying
 }

我个人会先运行一个查询来计算总行数,除以每页的行数,得到总页数,然后在if语句中使用它…等。