Wednesday, March 10, 2010

Php can only count to 10 (sort of)

Careful when casting large number to integer in php
You probably used to do this $val = (int)$val;
in php as a way to be sure that $val is an integer.

Some people do this for added security, since integers cannot contain any type of
script or html tags, so it's an easy way to sort-of sanitize the string.

But.. but... but ..... but....

Php like a child that can only count to 10, can only count to 2147483647
That's right, I did not expect this either.

Any number larger than 2147483647 php just does not know!
This means when you try to case any number larger than 2147483647 to integer using (int)$val, php will just return 2147483647

This is terribly wrong, certainly should be considered a bug!

If php does not know any integers larger than 2147483647, then it should raise error when you try to convert a larger number, not return the largest number it knows!

This can cause some weird problems in your code.
In my case I discovered this bug when working with Twitter API
The Twitter has billions of status messages, so all the latest status_ids are larger than 2147483647, so I was doing what I thought was a good practice and casting these status ids to integer with (int), but php was quietly replacing all the actual values with the 2147483647

By the way, it was php version 5.2.9, which is fairly new version. I mean, I would not be surprised to see this bug in php prior to 5, but in 5.2.9?!

That's crazy.

No comments:

Post a Comment