Adventures As Me


Can you spot the bug

Written 15 Jun 2005

Found in bBlog code: function maketimestamp($day,$month,$year,$hour,$minute) { // make timestamp format of YYYYMMDDHHMMSS $string = $year.$month.$day.$hour.$minute.'00'; $timestamp = mktime(substr($string,8,2), substr($string,10,2), substr($string,12,2), substr($string,4,2), substr($string,6,2), substr($string,0,4)); return $timestamp; }

Where in there is the bug? Ok, let me help you. Imagine that somewhere in the bBlog code, maketimestamp function is called with the following parameters: maketimestamp(1, 6, 2005, 6, 32); Let’s trace the function step by step. First, the arguments are concatentated in to a string: $string = $year.$month.$day.$hour.$minute.'00'; With our example $string now contains the following: '20056163200'; Next, this string is passed to the internal mktime function, where the parameters are supplied by substring our concatenated string. With our example, here are the values passed to mktime: $timestamp = mktime(20, 0, null, 61, 63, , 2005); Examining the PHP Documentation for mktime we find the parameters are: mktime ( [int hour [, int minute [, int second [, int month [, int day [, int year [, int is_dst]]]]]]] ) Because of the very unnecessary string concatenation in this user function, we pass invalid month and day values, and the values for hour, minute and second do not match the user supplied values.

When examining the function in response to a bug report, my first though was “what in the world was the developer thinking?” What need required the string creation? Why do we need a wrapper around a PHP internal function?

The fix is rather easy. Since I did not know the reason for the wrapper, I left it, but changed the body to: return mktime($hour, $minute, 00, $month, $day, $year);

Now the function works, returning the timestamp requested. :P

Related Posts