typing in PHP

PHP is probably my language of choice in this day and age, when it comes to web development. I would gladly build any web application in PHP over any of the other options, no matter their following. This following has cost me, however, although apparently I’m not the only one. Building applications in PHP comes with its own slew of crazy antics and events that need to be handled in order for applications to be secure. Partner this with the huge difference between being able to write PHP and being a PHP developer and you will find a growing chasm between security levels on the websites at large. One of the largest issues that PHP developers face is the topic of type checking. Although it stems from laziness, it is definitely a compound issue. PHP has little in the way of sanitization of input, and thusly, leads to SQL Injection and many other issues such as the register globals setting/flaw. Here I will show you about how to extract Integers and float values out of PHP’s scalar variables, where input begins life as a string.

var_dump( to_int("4"."6772.668988aAOKJNOINCOIN"));
var_dump( to_float("4"."6772.668988aAOKJNOINCOIN", 0));
var_dump( to_float("4"."6772.668988aAOKJNOINCOIN", 2));

This right here is the most beautiful pair of lines I have seen in far too long. PHP’s built in typing is pretty loose, allowing you to deal with Objects, Arrays and strings rather easily, but when it comes time to hit an integer things can be messy. I have seen a few scripts filled with regular expressions and all kinds of tests and garbage… Rarely do they actually do the most crucial item… Returning an integer typed value.

int(46772);
float(46773);
float(46772.67);

You may have noticed that not only is it returning the correct typed item, but it is also doing the most ill known thing – Value Rounding. All of this is carried out by two functions and is completely capable of being devised by everyone, although I have yet to find it being used in any circumstances, including type checking in apps like PHPBB and Drupal, both are applications I respect heavily. Here is the required code, take care.

function to_int($var)
{
	return (int)sprintf("%d", $var);
}
function to_float($var, $precision = null)
{
	if (isset($precision))
		return (float)sprintf("%.{$precision}f", $var);
	else
		return (float)sprintf("%f", $var);
}