Article 6DVRQ CodeSOD: Randomly Switching Images

CodeSOD: Randomly Switching Images

by
Remy Porter
from The Daily WTF on (#6DVRQ)

Ronald writes:

I've been asked to take over a website. The first thing I found was this little gem. I'm afraid to go on...

That "gem" is in the file header.php, which is included in every page on the site:

<?PHP$start = 1;$total = 16;$pic = rand($start, $total);switch($pic){case "1":echo'<img src="'.$base.'img/header/random_img_01.png"/>';break;case "2":echo'<img src="'.$base.'img/header/random_img_02.png"/>';break;case "3":echo'<img src="'.$base.'img/header/random_img_03.png"/>';break;case "4":echo'<img src="'.$base.'img/header/random_img_04.png"/>';break;case "5":echo'<img src="'.$base.'img/header/random_img_05.png"/>';break;case "6":echo'<img src="'.$base.'img/header/random_img_06.png"/>';break;case "7":echo'<img src="'.$base.'img/header/random_img_07.png"/>';break;case "8":echo'<img src="'.$base.'img/header/random_img_08.png"/>';break;case "9":echo'<img src="'.$base.'img/header/random_img_09.png"/>';break;case "10":echo'<img src="'.$base.'img/header/random_img_10.png"/>';break;case "11":echo'<img src="'.$base.'img/header/random_img_11.png"/>';break;case "12":echo'<img src="'.$base.'img/header/random_img_12.png"/>';break;case "13":echo'<img src="'.$base.'img/header/random_img_13.png"/>';break;case "14":echo'<img src="'.$base.'img/header/random_img_14.png"/>';break;case "15":echo'<img src="'.$base.'img/header/random_img_15.png"/>';break;case "16":echo'<img src="'.$base.'img/header/random_img_16.png"/>';break;}?>

That's certainly one way to set a random banner image on every page load.

Now, I wasn't certain if PHP's rand function was inclusive or not, so I had to look up the documentation to see if there was a bug in this code. There is not, but the PHP rand page is plastered with warnings and caveats. The fact that it's not cryptographically secure is worth noting, but absolutely reasonable. The drama about getrandmax and mt_rand is delightful, and then it's worth noting that as of 7.1 rand and mt_rand are the same thing, but the documentation is unclear if that means getrandmax and mt_getrandmax are (it seems like they should be, and it seems like they are in practice, but it'd be nice to have that explicitly spelled out).

Every time I look something up on the PHP documentation, I find a new thing that leaves me scratching my head.

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