Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
285 views
in Technique[技术] by (71.8m points)

php - How to check whether a variable in $_GET Array is an integer?

I have a page like so:

http://sitename/gallery.php?page=2

It has pagination links at the bottom by which we can browse. Everytime the page numbers are clicked, it would send a GET request with parameters page=1 or page=2 and so on ...

When I store these values to $page from teh $_GET variable, it is a string value. I can convert it to an integer using (int) like this:

if(!empty($_GET['page'])){
       $page = (int)$_GET['page'];
       echo "Page Number: ".$page;
}

But how can I make sure that the value passed is an integer only and not other crap?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Using filters:

if (null !== ($page = filter_input(INPUT_GET, 'page', FILTER_VALIDATE_INT, FILTER_NULL_ON_FAILURE))) {
    // $page is now an integer
}

This also checks whether the variable appears in the query string at the same time. If you want to differentiate between missing and invalid you have to leave off the last argument to filter_input():

$page = filter_input(INPUT_GET, 'page', FILTER_VALIDATE_INT);
// $page can be null (not present), false (present but not valid) or a valid integer

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...