Validating integer input in PHPWhen developing websites today, you need to be afraid of all information being submitted to your PHP scripts from the internet. Every bit of information that comes in needs to be checked to make sure it is actually what you were expecting. Here is a quick and easy function to validate integer input coming in through a URL (GET request).
function validateint($inData) {
$intRetVal = -1;
$IntValue = intval($inData);
$StrValue = strval($IntValue);
if($StrValue == $inData) {
$intRetVal = $IntValue;
}
return $intRetVal;
}
As you can see, this function simply converts the input to an integer and then back to a string. During this conversion, if the input was not a valid integer, the resulting string would not be the same as the data sent in. We then compare the twice converted string to the original input data and if they are the same, we return the converted integer value. In the case of this particular function, it returns -1 if the input data is not an integer, and therefore this function wouldn't work for pages which are expecting negative values. You could easily modify this function to account for that situation. You would use this function in your PHP site, something like this...
$intUserInput = validateint($_GET['productid']);
if($intUserInput > -1) {
// The input is a valid positive integer, so we can now use it
print "The ID '".$intUserInput."' is valid.";
} else {
// The input is not a valid positive integer.
print "Invalid integer given.";
}
Your website will be much more secure if you perform data checks of this sort on all data being sent to your script from the internet. Author: DPAK Created: Sep 20 2005 Categories: PHP TechByte #19 Warning: By visiting this site and/or by using any information contained herein, you agree to the Techbytes.ca terms of use.
Add a comment about this TechByteIf you wish to add a comment regarding this TechByte, please use the form below. Please note that by submitting comments using this form you are allowing all of the information submitted to be visible on this website. Any comments submitted using this form will only be shown on the website if they are approved by the administrators of this site. IF APPROVED, COMMENTS MAY TAKE SEVERAL DAYS TO BE POSTED. Other TechBytes: |
|

