开发者

Ensuring the information after ? is an integer

I've moved from HTML to PHP coding, so when I wanted to make a link for my news page I used HREF to take the id for the row as a link and make the title of the piece the viewable/clickable link:

echo "<a href=news.php?id=".$row{'id'};
echo ">";
echo ucwords(strtolower($row{'newstitle'}));
echo "</a>开发者_开发问答;";

So when someone clicks on the title it redirects to the article and the address bar becomes (obviously this is an example): http://site.com/news.php?id=1

How can I validate that the information after the ? is id=int (it will always be a number) and not some user code or other input that could damage the site? I've looked at ways of Sanitizing/Validating the code, but all the examples I've found have been to do with entering information into forms that are then used in the address rather than simply ensuring the address is valid, hence turning to here for assistance. Thanks


You should use the filter module:

$id = filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT);
if ($id === false) {
     // not an integer
}

Or you can use ctype_digit() to check if a variable is composed only of decimal digits:

if (ctype_digit($_GET['id'])) {
    // it's an integer
} else {
    // not an integer
}

Or shorter:

ctype_digit($_GET['id']) or die("oops that's not an integer!");

But die or exit would make your code less testable.


is_numeric would work too, but it would return true for any string representation of a number, not only integers.


Try this

<?php
if (is_int($_GET["id"])) {
echo "is integer\n";
} else {
echo "is not an integer\n";
}
?>


If you have excluded 0 as a valid number for your integer id, you can simply do the following:

$id = (int) $_GET['id'];
if (!$id) {
    # no number -or- 0 given
} else {
   # regardless what have been given, it has been converted at least to some integer.
}

That's by casting. Now $id is always an integer so more safe to use.

However, most often you need to check as well that the number is non-negative:

$id = max(0, $_GET['id']);

The max function does take care of casting $_GET['id'] into an integer. It ensures that the id is 0 or higher in case the provided value was greater than 0. If it was 0 or lower, 0 is the maximum number.

If you then need to actually validate the input more strictly, you can turn it back into a string for comparison reasons:

if ("$id" === $_GET['id'])
{
   # Input was done as a string representation of the integer value.
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜