CodeSOD: Around 20 Meg

Michael was assigned a short, investigatory ticket. You see, their PHP application allowed file uploads. They had a rule: the files should never be larger than 20MB. They had files which were larger. Not much larger, but larger. Michael was tasked with figuring out what was wrong.

Given that the error was less than half a megabyte, Michael had a pretty good guess about why this was.

if (round($uploadedFile->getSize() / 1024 / 1024) > 20) { [ ... throw some error message ] }

The developer's instincts weren't entirely bad. Take the number of bytes, divide by 1024 twice to get it down to megabytes, and then compare against twenty. It's probably not how I'd write it, but it's not wrong- at least not until you start rounding the number off.

Why was the developer rounding in the first place?

"Because 20 is an integer, and I wanted to compare integers. So I rounded. PHP doesn't have a built in trunc method."

Pedantically true, as there's nothing called trunc or truncate in PHP, but it does have a floor and an intval method, both of which discard decimal digits (but behave slightly differently). In this case, either one would have worked.

[Advertisement] Keep the plebs out of prod. Restrict NuGet feed privileges with ProGet. Learn more.

This post originally appeared on The Daily WTF.

Leave a Reply

Your email address will not be published. Required fields are marked *