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

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?

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

Use filter_var() with the FILTER_VALIDATE_INT filter on it, and check the return value.

Use is_numeric().
is_int() will not work because GET parameters are always string.

I've left a few comments here and there. Thanks to weak typing, functions like empty and isset tend to be unreliable. The quickest way to check if a parameter is an int or not IMO would be this:
if (array_key_exists('page',$_GET) && ($_GET['page'] == (int) $_GET['page']))
Casting to int and then compare the respective values will return true only when $_GET['page'] is a valid int. If you want to use strict type comparison for some reason (some do), you could double cast:
if (array_key_exists('page',$_GET) && ($_GET['page'] === (string)((int) $_GET['page'])))
But in this particular case, I can't really see why you would want to do that

this is a way how to check parameter if it is intetger or not.
if (is_int((int) $_GET['user_id']) && (int) $_GET['user_id'] != 0) {
$user_id = $_GET['user_id'];
}

Using is_int won't help, probably. All incoming parameters (including $_GET and $_POST) are parsed as strings by PHP. The is_int function checks the datatype, not the value. ctype_digit checks for only digits though:
if(isset($_GET['page']) && ctype_digit($_GET['page']){
$page = (int)$_GET['page'];
echo "Page Number: ".$page;
}

if(!empty($_GET['page']) and is_numeric($_GET['page'])){
$page = (int)$_GET['page'];
echo "Page Number: ".$page;
}
is_numeric is probably what you need.

You can also check with
isNAN($_GET['something']);//is_numeric($_GET['something'])
it returns a boolean value(true,flase)....if its true then it is not an integer,if false its an integer.

if (isset($_GET['page']) && (($get_page_filtered = filter_var($_GET['page'], FILTER_VALIDATE_INT)) !== FALSE) {
$get_page_int = $get_page_filtered;
}
#see https://stackoverflow.com/a/41868665/6758130

Related

Mongodb how to get the result through php?id=1 [duplicate]

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?
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
Use filter_var() with the FILTER_VALIDATE_INT filter on it, and check the return value.
Use is_numeric().
is_int() will not work because GET parameters are always string.
I've left a few comments here and there. Thanks to weak typing, functions like empty and isset tend to be unreliable. The quickest way to check if a parameter is an int or not IMO would be this:
if (array_key_exists('page',$_GET) && ($_GET['page'] == (int) $_GET['page']))
Casting to int and then compare the respective values will return true only when $_GET['page'] is a valid int. If you want to use strict type comparison for some reason (some do), you could double cast:
if (array_key_exists('page',$_GET) && ($_GET['page'] === (string)((int) $_GET['page'])))
But in this particular case, I can't really see why you would want to do that
this is a way how to check parameter if it is intetger or not.
if (is_int((int) $_GET['user_id']) && (int) $_GET['user_id'] != 0) {
$user_id = $_GET['user_id'];
}
Using is_int won't help, probably. All incoming parameters (including $_GET and $_POST) are parsed as strings by PHP. The is_int function checks the datatype, not the value. ctype_digit checks for only digits though:
if(isset($_GET['page']) && ctype_digit($_GET['page']){
$page = (int)$_GET['page'];
echo "Page Number: ".$page;
}
if(!empty($_GET['page']) and is_numeric($_GET['page'])){
$page = (int)$_GET['page'];
echo "Page Number: ".$page;
}
is_numeric is probably what you need.
You can also check with
isNAN($_GET['something']);//is_numeric($_GET['something'])
it returns a boolean value(true,flase)....if its true then it is not an integer,if false its an integer.
if (isset($_GET['page']) && (($get_page_filtered = filter_var($_GET['page'], FILTER_VALIDATE_INT)) !== FALSE) {
$get_page_int = $get_page_filtered;
}
#see https://stackoverflow.com/a/41868665/6758130

How to detect when "0" is supplied as a form/$_POST value?

I'm trying to determine whether or not there is a value passed, but the value CAN be 0 ...
isset always returns true, and empty returns false because the value is 0
How can I get around this?
try
bool array_key_exists ( mixed $key , array $array )
like
if (array_key_exists("var1", $_POST)) {
// positive case, var1 was posted
if ($_POST["var1"] == 0){
// var1 was posted and 0
}else{
// var1 was posted and is not 0
}
}
more details are given at the docs.
The values of the $_POST array is all strings. Use the === operator:
if ($_POST['key'] === '0') {
// do things
}
Try this
if (isset($_POST['name']) && $_POST['name'] != 0)) {
/your Code/
}
What about simply checking whether the value is empty:
if (isset($_POST['key']) && $_POST['key'] !== '')) {
//'key' is set and not empty
}
All post values are strings, so consider:
isset($a[i]) && strlen($a[i])
Which will be true if and only if a value (except "an empty string") is supplied. Unlike with empty, which would return FALSE, this will also detect when "0" was passed as a value. Unlike the proposed solution, it will not be true when "" was supplied: thus it truly detects when a value was passed.
Also, array_key_exists and isset for $_POST keys will work the same, as there will no NULL values; arguably the critical check is that for a non-empty string. Once a value has been determined to exist (per the above/desired rules), it can be processed as appropriate - e.g. if ($a[i] > 0) or if ($a[i] == 0).

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.
}

is_int() cannot check $_GET in PHP?

Here is my code:
<?php
$id = $_GET["id"];
if (is_int($id) === FALSE) {
header('HTTP/1.1 404 Not Found');
exit('404, page not found');
}
?>
It always enters inside the if.
is_int checks that the data type is an integer, but everything in $_GET will be a string. Therefore, it will always return false.
In a pinch, you could cast to an integer and then check for != 0.
$id = isset($_GET['id']) ? (int) $_GET['id'] : null;
if (!$id) { // === 0 || === null
header('HTTP/1.1 404 Not Found');
exit('404, page not found');
}
But a more robust solution would involve some type of input string validation / filtering, like PHP's built-in filter_input_array().
(Edited post on Oct/13 since it is still receiving upvotes and it was somewhat confusingly worded.)
User input in $_GET array (as well as the other superglobals) all take the form of strings.
is_int checks the type (i.e. string) of the value, not whether it contains integer-like values. For verification that the input is an integer string, I would suggest either something like ctype_digit or an integer filter (FILTER_VALIDATE_INT—this has the benefit of actually changing the value to type integer). Of course you could also typecast it with (int).
From the PHP documentation for is_int:
Note: To test if a variable is a
number or a numeric string (such as
form input, which is always a string),
you must use is_numeric().
Any user input comes in as a string, because PHP has no way to tell what data type you expect the data to be.
Cast it to an integer or use a regex if you want to make sure it's an integer.
<?php
$id = $_GET["id"];
if ((int) $id == 0) {
header('HTTP/1.1 404 Not Found');
exit('404, page not found');
}
?>
Try using is_numeric instead of is_int. is_numeric checks to see if it is given something that can be a number ($_GET returns strings I think). is_int checks to see if the variable is of type int
Use is_numeric() to evaluate the content and is_int() to evaluate the type.
Or, you could just use a regex match to check if the string is an integer.
if(preg_match('/^\d+$/',$_GET['id'])) {
// is an integer
}

In where shall I use isset() and !empty()

I read somewhere that the isset() function treats an empty string as TRUE, therefore isset() is not an effective way to validate text inputs and text boxes from a HTML form.
So you can use empty() to check that a user typed something.
Is it true that the isset() function treats an empty string as TRUE?
Then in which situations should I use isset()? Should I always use !empty() to check if there is something?
For example instead of
if(isset($_GET['gender']))...
Using this
if(!empty($_GET['gender']))...
isset vs. !empty
FTA:
"isset() checks if a variable has a
value including (False, 0 or empty
string), but not NULL. Returns TRUE
if var exists; FALSE otherwise.
On the other hand the empty() function
checks if the variable has an empty
value empty string, 0, NULL or
False. Returns FALSE if var has a
non-empty and non-zero value."
In the most general way :
isset tests if a variable (or an element of an array, or a property of an object) exists (and is not null)
empty tests if a variable (...) contains some non-empty data.
To answer question 1 :
$str = '';
var_dump(isset($str));
gives
boolean true
Because the variable $str exists.
And question 2 :
You should use isset to determine whether a variable exists ; for instance, if you are getting some data as an array, you might need to check if a key isset in that array.
Think about $_GET / $_POST, for instance.
Now, to work on its value, when you know there is such a value : that is the job of empty.
Neither is a good way to check for valid input.
isset() is not sufficient because – as has been noted already – it considers an empty string to be a valid value.
! empty() is not sufficient either because it rejects '0', which could be a valid value.
Using isset() combined with an equality check against an empty string is the bare minimum that you need to verify that an incoming parameter has a value without creating false negatives:
if( isset($_GET['gender']) and ($_GET['gender'] != '') )
{
...
}
But by "bare minimum", I mean exactly that. All the above code does is determine whether there is some value for $_GET['gender']. It does not determine whether the value for $_GET['gender'] is valid (e.g., one of ("Male", "Female","FileNotFound")).
For that, see Josh Davis's answer.
isset is intended to be used only for variables and not just values, so isset("foobar") will raise an error. As of PHP 5.5, empty supports both variables and expressions.
So your first question should rather be if isset returns true for a variable that holds an empty string. And the answer is:
$var = "";
var_dump(isset($var));
The type comparison tables in PHP’s manual is quite handy for such questions.
isset basically checks if a variable has any value other than null since non-existing variables have always the value null. empty is kind of the counter part to isset but does also treat the integer value 0 and the string value "0" as empty. (Again, take a look at the type comparison tables.)
If you have a $_POST['param'] and assume it's string type then
isset($_POST['param']) && $_POST['param'] != '' && $_POST['param'] != '0'
is identical to
!empty($_POST['param'])
isset() is not an effective way to validate text inputs and text boxes from a HTML form
You can rewrite that as "isset() is not a way to validate input." To validate input, use PHP's filter extension. filter_has_var() will tell you whether the variable exists while filter_input() will actually filter and/or sanitize the input.
Note that you don't have to use filter_has_var() prior to filter_input() and if you ask for a variable that is not set, filter_input() will simply return null.
When and how to use:
isset()
True for 0, 1, empty string, a string containing a value, true, false
False for null
e.g
$status = 0
if (isset($status)) // True
$status = null
if (isset($status)) // False
Empty
False for 1, a string containing a value, true
True for null, empty string, 0, false
e.g
$status = 0
if(empty($status)) // true
$status = 1
if(empty($status)) // False
isset() vs empty() vs is_null()
isset is used to determine if an instance of something exists that is, if a variable has been instantiated... it is not concerned with the value of the parameter...
Pascal MARTIN... +1
...
empty() does not generate a warning if the variable does not exist... therefore, isset() is preferred when testing for the existence of a variable when you intend to modify it...
isset() is used to check if the variable is set with the value or not and Empty() is used to check if a given variable is empty or not.
isset() returns true when the variable is not null whereas Empty() returns true if the variable is an empty string.
isset($variable) === (#$variable !== null)
empty($variable) === (#$variable == false)
I came here looking for a quick way to check if a variable has any content in it. None of the answers here provided a full solution, so here it is:
It's enough to check if the input is '' or null, because:
Request URL .../test.php?var= results in $_GET['var'] = ''
Request URL .../test.php results in $_GET['var'] = null
isset() returns false only when the variable exists and is not set to null, so if you use it you'll get true for empty strings ('').
empty() considers both null and '' empty, but it also considers '0' empty, which is a problem in some use cases.
If you want to treat '0' as empty, then use empty(). Otherwise use the following check:
$var .'' !== '' evaluates to false only for the following inputs:
''
null
false
I use the following check to also filter out strings with only spaces and line breaks:
function hasContent($var){
return trim($var .'') !== '';
}
Using empty is enough:
if(!empty($variable)){
// Do stuff
}
Additionally, if you want an integer value it might also be worth checking that intval($variable) !== FALSE.
I use the following to avoid notices, this checks if the var it's declarated on GET or POST and with the # prefix you can safely check if is not empty and avoid the notice if the var is not set:
if( isset($_GET['var']) && #$_GET['var']!='' ){
//Is not empty, do something
}
$var = '';
// Evaluates to true because $var is empty
if ( empty($var) ) {
echo '$var is either 0, empty, or not set at all';
}
// Evaluates as true because $var is set
if ( isset($var) ) {
echo '$var is set even though it is empty';
}
Source: Php.net
isset() tests if a variable is set and not null:
http://us.php.net/manual/en/function.isset.php
empty() can return true when the variable is set to certain values:
http://us.php.net/manual/en/function.empty.php
<?php
$the_var = 0;
if (isset($the_var)) {
echo "set";
} else {
echo "not set";
}
echo "\n";
if (empty($the_var)) {
echo "empty";
} else {
echo "not empty";
}
?>
!empty will do the trick. if you need only to check data exists or not then use isset other empty can handle other validations
<?php
$array = [ "name_new" => "print me"];
if (!empty($array['name'])){
echo $array['name'];
}
//output : {nothing}
////////////////////////////////////////////////////////////////////
$array2 = [ "name" => NULL];
if (!empty($array2['name'])){
echo $array2['name'];
}
//output : {nothing}
////////////////////////////////////////////////////////////////////
$array3 = [ "name" => ""];
if (!empty($array3['name'])){
echo $array3['name'];
}
//output : {nothing}
////////////////////////////////////////////////////////////////////
$array4 = [1,2];
if (!empty($array4['name'])){
echo $array4['name'];
}
//output : {nothing}
////////////////////////////////////////////////////////////////////
$array5 = [];
if (!empty($array5['name'])){
echo $array5['name'];
}
//output : {nothing}
?>
Please consider behavior may change on different PHP versions
From documentation
isset() Returns TRUE if var exists and has any value other than NULL. FALSE otherwise
https://www.php.net/manual/en/function.isset.php
empty() does not exist or if its value equals FALSE
https://www.php.net/manual/en/function.empty.php
(empty($x) == (!isset($x) || !$x)) // returns true;
(!empty($x) == (isset($x) && $x)) // returns true;
When in doubt, use this one to check your Value and to clear your head on the difference between isset and empty.
if(empty($yourVal)) {
echo "YES empty - $yourVal"; // no result
}
if(!empty($yourVal)) {
echo "<P>NOT !empty- $yourVal"; // result
}
if(isset($yourVal)) {
echo "<P>YES isset - $yourVal"; // found yourVal, but result can still be none - yourVal is set without value
}
if(!isset($yourVal)) {
echo "<P>NO !isset - $yourVal"; // $yourVal is not set, therefore no result
}

Categories