*weird* PHP bug
This isn't a bug in PHP, but a bug in my code. I thought I'd share it here so that others can learn from it, or at least have a good laugh at my expense. :-)
I was working on some code today that allowed date-based searching. You could search by month, day, or year, and each parameter was optional. The results screen would also print up the search paramters that you used. The code I used for getting the name of the month was something like this:
Looks reasonable, right? Well, there's two more parameters for the mktime() call that I did not specify: day of month, and year. I got a bug report today that people were searching for entries from Februrary, and it was saying "March" on the results screen.
After some digging around, I discovered that mktime() uses the current timestamp to "fill in" any missing parameters! Since today is the 30th of April, the above mktime() call generated a time stamp for Februrary 30th, which PHP converted into March 2nd, and the date() call got March as the month.
The fix for this was to change the mktime call like this:
Now all calls to mktime() get the timestamp for the 1st of the month, and the bug if fixed.
Comments or insults are welcome. :-)
I was working on some code today that allowed date-based searching. You could search by month, day, or year, and each parameter was optional. The results screen would also print up the search paramters that you used. The code I used for getting the name of the month was something like this:
if ($search["month"]) {
$timestamp=mktime(0, 0, 0, $search["month"]);
$text_month=date("F", $timestamp);
}Looks reasonable, right? Well, there's two more parameters for the mktime() call that I did not specify: day of month, and year. I got a bug report today that people were searching for entries from Februrary, and it was saying "March" on the results screen.
After some digging around, I discovered that mktime() uses the current timestamp to "fill in" any missing parameters! Since today is the 30th of April, the above mktime() call generated a time stamp for Februrary 30th, which PHP converted into March 2nd, and the date() call got March as the month.
The fix for this was to change the mktime call like this:
$timestamp=mktime(0, 0, 0, $search["month"], 1);
Now all calls to mktime() get the timestamp for the 1st of the month, and the bug if fixed.
Comments or insults are welcome. :-)
