I am trying to make sure the GET string is set in the URL and that it's value is an integer, but I can't get this to work.
if (isset($_GET['allusers']) && is_int($_GET['allusers'])) {
echo "works";
}
Am I doing something wrong with my parentheses?
A $_GET variable can't be an integer. It'll always be a string.
To test is it's a numeric string, use is_numeric():
if ( isset($_GET['allusers']) && is_numeric($_GET['allusers']) )
{
echo "works";
}
In your code
isset($_GET['allusers'])
will be evaluated to be true but
is_int($_GET['allusers']) will not as the value of $_GET is a string not int you can modify your code as
if (isset($_GET['allusers']) && is_int(intval($_GET['allusers']))) {
echo "works";
}
This will work
Use ctype_digit if you are expecting only non-negative integers. This will give the best result in those cases since it allows only the numbers 0-9.
Note that is_numeric will return true for strings which can be converted to integers, both negatives and floats. A few examples of what is_numeric will consider to be true:
0xF5 (hexadecimal)
-.0e-000 (a strange way of expressing 0.0)
-0.4
is_int returns false on a string, which is what a GET variable will be.
var_dump(is_int("23"));
bool(false)
You should be using is_numeric instad.
Related
I need to take a string and return true if only positive OR negative numbers are in the string. Is there a way to do this?
$rating = "-25";
if (!ctype_digit($rating)) {
echo "Not a digit.";
}
else {
echo "Is a digit.";
}
Result:
Not a digit.
Need Result:
Is a digit.
ctype_digit() works on values that consists only of digits.
Where $rating = -25; is false as it is being treated as a ASCII code in this particular case (explained below), and "-25" is invalid because - is not a digit.
You could type juggle but I think you're looking for is_numeric()
echo is_numeric( "-25"); or echo ctype_digit((integer) $var);
However the latter would return true if the string cannot be cast to an integer. It will have the value of 0 if that's the case.
Important:
If you pass a literal integer in range of -128 and 255 to ctype_digit() the value is converted to the character defined in the ASCII table. If its not a number, false is expected. Any other integer value is normal expected behavior.
filter_var is the correct answer to this question and has been around since 5.2, according to the documentation.
filter_var will return filtered data or false if the string is not a valid integer.
var_dump(filter_var("1", FILTER_VALIDATE_INT) !== false);
var_dump(filter_var("0", FILTER_VALIDATE_INT) !== false);
var_dump(filter_var("-1", FILTER_VALIDATE_INT) !== false);
Result:
test.php:1:boolean true
test.php:2:boolean true
test.php:3:boolean true
Note that you must perform a comparison with false instead of logical ! otherwise it will fail when comparing with 0.
Why below code is printing the "here", it should be "there"
$a = "171E-10314";
if($a == '0')
{
echo "here";
}
else
{
echo "there";
}
PHP automatically parses anything that's a number or an integer inside a string to an integer. "171E-10314" is another way of telling PHP to calculate 171 * 10 ^ -10314, which equates to (almost) 0. So when you do $a == '0', the '0' will equate to 0 according to PHP, and it returns true.
If you want to compare strings, use the strcmp function or use the strict comparator ===.
when you use the == comparison, PHP tries to cast to different data types to check for a match like that
in your case:
'0' becomes 0
"171E-10314" is still mathematically almost 0 but I think PHP just rounds it to 0 due to the resolution of float.
check this link for a visual representation:
http://www.wolframalpha.com/input/?i=171E-10314
As per the answers given I tried to convert the string into numerical:
$a = "171E-10314" + 0;
print $a;
And I got output as 0.
Thats why it is printing here.
Use === /*(this is for the 30 character)*/
I have strings of the following form: "37", "42", "7".
I need to transform them into integers. I can use intval. But I want to check if the string was in the expected format (by not expected format I mean, for example, "abc" or "a7"). How can I do it before or after use of the intval?
As far as I know intval returns 1 if the argument was not in the appropriate format. If it is the case, there is not way to check if the argument was the good format just by analyzing the output of the intval.
You can use
ctype_digit()
http://ro2.php.net/ctype_digit
You're probably looking for filter_var.
$input = '5';
filter_var($input, FILTER_VALIDATE_INT); // returns 5
$input = 'asdf';
filter_var($input, FILTER_VALIDATE_INT); // returns false
There are also many other options you can pass into this function. I believe it was designed as a way to validate form submissions.
ctype_digit($x) && ($x == floor($x))
You can use the function is_numeric(). It should return true if it is a number, false if there are letters in the mix.
Mediocre solution, but you could do:
preg_match('/^[0-9]*$/', $value)
How about (int)$value == $value?
This would cast the value to an int, so that the left hand is definately an integer, and then checks if an untyped comparison is true.
Why does is_int always return false in the following situation?
echo $_GET['id']; //3
if(is_int($_GET['id']))
echo 'int'; //not executed
Why does is_int always return false?
Because $_GET["id"] is a string, even if it happens to contain a number.
Your options:
Use the filter extension. filter_input(INPUT_GET, "id", FILTER_VALIDATE_INT) will return an integer typed variable if the variable exists, is not an array, represents an integer and that integer is within the valid bounds. Otherwise it will return false.
Force cast it to integer (int)$_GET["id"] - probably not what you want because you can't properly handle errors (i.e. "id" not being a number)
Use ctype_digit() to make sure the string consists only of numbers, and therefore is an integer - technically, this returns true also with very large numbers that are beyond int's scope, but I doubt this will be a problem. However, note that this method will not recognize negative numbers.
Do not use:
is_numeric() because it will also recognize float values (1.23132)
Because HTTP variables are always either strings, or arrays. And the elements of arrays are always strings or arrays.
You want the is_numeric function, which will return true for "4". Either that, or cast the variable to an int $foo = (int) $_GET['id']...
Checking for integers using is_int($value) will return false for strings.
Casting the value -- is_int((int) $value) -- won't help because strings and floats will result in false positive.
is_numeric($value) will reject non numeric strings, but floats still pass.
But the thing is, a float cast to integer won't equal itself if it's not an integer. So I came up with something like this:
$isInt = (is_numeric($value) && (int) $value == $value);
It works fine for integers and strings ... and some floating numbers.
But unfortunately, this will not work for some float integers.
$number = pow(125, 1/3); // float(5) -- cube root of 125
var_dump((int) $number == $number); // bool(false)
But that's a whole different question.
How i fixed it:
$int_id = (int) $_GET["id"];
if((string)$int_id == $_GET["id"]) {
echo $_GET["id"];
}
It's probably stored as a string in the $_GET, cast it to an int.
Because $_GET is an array of strings.
To check if the get parameter contains an integer you should use is_numeric()
Because $_GET['id'] is a string like other parts of query string. You are not converting it to integer anywhere so is_int return false.
The dirty solution I'm using is this:
$val = trim($_GET['id']);
$cnd = ($val == (int)$val);
echo $cnd ? "It's an int" : "Not an int";
Apart from the obvious (ugly code that hides its workings behind specifics of the php engine), does anybody know cases where this goes wrong?
Prabably best way to check if value from GET or POST is integer is check by preg_match
if( preg_match('/^[0-9]+$/', $_GET['id'] ){
echo "is int";
}
You can possibly try the intval() which can be used to test the value of your var. e.g
If(intval($_GET['ID']==0)
The function will check if the var is integer and return TRUE if not FALSE
It seems that PHP's === operator is case sensitive. So is there a reason to use strcmp()?
Is it safe to do something like the following?
if ($password === $password2) { ... }
The reason to use it is because strcmp
returns < 0 if str1 is less than str2; > 0 if str1 is greater than str2, and 0 if they are equal.
=== only returns true or false, it doesn't tell you which is the "greater" string.
You should never use == for string comparison. === is OK.
$something = 0;
echo ('password123' == $something) ? 'true' : 'false';
Just run the above code and you'll see why.
$something = 0;
echo ('password123' === $something) ? 'true' : 'false';
Now, that's a little better.
Don't use == in PHP. It will not do what you expect. Even if you are comparing strings to strings, PHP will implicitly cast them to floats and do a numerical comparison if they appear numerical.
For example '1e3' == '1000' returns true. You should use === instead.
Well...according to this PHP bug report, you can even get 0wned.
<?php
$pass = isset($_GET['pass']) ? $_GET['pass'] : '';
// Query /?pass[]= will authorize user
//strcmp and strcasecmp both are prone to this hack
if ( strcasecmp( $pass, '123456' ) == 0 ){
echo 'You successfully logged in.';
}
?>
It gives you a warning, but still bypass the comparison.
You should be doing === as #postfuturist suggested.
Always remember, when comparing strings, you should use the === operator (strict comparison) and not == operator (loose comparison).
Summing up all answers:
== is a bad idea for string comparisons.
It will give you "surprising" results in many cases. Don't trust it.
=== is fine, and will give you the best performance.
strcmp() should be used if you need to determine which string is "greater", typically for sorting operations.
Using == might be dangerous.
Note, that it would cast the variable to another data type if the two differs.
Examples:
echo (1 == '1') ? 'true' : 'false';
echo (1 == true) ? 'true' : 'false';
As you can see, these two are from different types, but the result is true, which might not be what your code will expect.
Using ===, however, is recommended as test shows that it's a bit faster than strcmp() and its case-insensitive alternative strcasecmp().
Quick googling yells this speed comparison: http://snipplr.com/view/758/
strcmp() and === are both case sensitive, but === is much faster.
Sample code: Speed Test: strcmp vs ===
strcmp will return different values based on the environment it is running in (Linux/Windows)!
The reason is the that it has a bug as the bug report says - Bug #53999strcmp() doesn't always return -1, 0, or 1
You can use strcmp() if you wish to order/compare strings lexicographically. If you just wish to check for equality then == is just fine.
Also, the function can help in sorting. To be more clear about sorting. strcmp() returns less than 0 if string1 sorts before string2, greater than 0 if string2 sorts before string1 or 0 if they are the same. For example
$first_string = "aabo";
$second_string = "aaao";
echo $n = strcmp($first_string, $second_string);
The function will return greater than zero, as aaao is sorting before aabo.
if ($password === $password2) { ... } is not a safe thing to do when comparing passwords or password hashes where one of the inputs is user controlled.
In that case it creates a timing oracle allowing an attacker to derive the actual password hash from execution time differences.
Use if (hash_equals($password, $password2)) { ... } instead, because hash_equals performs "timing attack safe string comparison".
In PHP, instead of using alphabetical sorting, use the ASCII value of the character to make the comparison.
Lowercase letters have a higher ASCII value than capitals. It's better to use the identity operator === to make this sort of comparison. strcmp() is a function to perform binary safe string comparisons. It takes two strings as arguments and returns < 0 if str1 is less than str2; > 0 if str1 is greater than str2, and 0 if they are equal. There is also a case-insensitive version named strcasecmp() that first converts strings to lowercase and then compares them.