
Originally Posted by
james438
Got it.
It appears that $_GET is always cast by php as a string.
All the PHP HTTP variables ($_GET, $_POST, etc.) are strings, regardless of content. This isn't PHP specific; it's how the HTTP standard works.

Originally Posted by
james438
That being the case, how can a string be converted to an integer? This can be done via (int)
You're right. The easiest (and I believe fastest?) way is to cast it to an int using (int) $variable
.

Originally Posted by
james438
Note that in the case of "3.5" or "2drtg45" or "23" or "hi" the results will be converted to "3", "2", "23", and "0". 3.5 is numeric and not an integer.
Int casting in PHP works per the following table. See PHP's Integers: Converting to integer for the full details and edge cases.
bool |
Simple; as below |
true |
1 |
false |
0 |
float |
Rounded towards zero |
5.8 |
5 |
-5.8 |
-5 |
string |
If the string is numeric or it starts with a numeric, it is treated as that number. Otherwise it is zero. |
"8" |
8 |
"6.8" |
6 |
"4 words" |
4 |
"Words, 6 words" |
0 |
"Words" |
0 |
To check if a string is a valid integer, you can use filter_var with the FILTER_VALIDATE_INT
filter.
PHP Code:
<?php
$filteredId = filter_var($_GET['id'], FILTER_VALIDATE_INT);
if($filteredId === false) {
echo 'is not an integer';
} else {
echo $filteredId . ' is an integer (type: ' . gettype($filteredId) . ')';
}
?>
Notes:
- If the filter is validated, it will return the filtered data. In the sample code above, if the filter is successful, the output ($filteredId) will be an int.
- If it is invalid, it will return false. Make sure you use triple equal signs! If you use
if($filteredId == false)
, it will not work properly if the user input is 0. - Never echo user supplied data without sanitising, or you'll probably be open to XSS attacks.
Bookmarks