Article 62939 CodeSOD: Around 20 Meg

CodeSOD: Around 20 Meg

by
Remy Porter
from The Daily WTF on (#62939)

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. But someone had uploaded 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.

proget-icon.png [Advertisement] Keep the plebs out of prod. Restrict NuGet feed privileges with ProGet. Learn more.
External Content
Source RSS or Atom Feed
Feed Location http://syndication.thedailywtf.com/TheDailyWtf
Feed Title The Daily WTF
Feed Link http://thedailywtf.com/
Reply 0 comments