"While exploring a rather large PHP codebase at my new job," Anthony C writes, "I kept coming across a rather curious pattern from the previous developers:
src="content.php?NoCache=<?php $random = make_random_code(); echo("$random"); ?>"
"Clearly, it was just being used to prevent 'content.php' (or whatever page) from being cached, so I never bothered looking into it any further. Eventually though, curiousity got the better of me, and I just had t take a look...
<?php
// Function to generate a random code
function make_random_code() {
// Salt value
$salt = "abcdefghijklmnopqrstuvwxyz0123456789";
// Use the time to create a random value
srand((double)microtime()*1000000);
// Set i = 0
$i = 0;
// Do while i <= 7
while ($i <= 7) {
// Generate a random number
$num = rand() % 33;
// Create a tmp value
$tmp = substr($salt, $num, 1);
// Create the random code
$random_code = $random_code . $tmp;
// Increment i by 1
$i++;
}
// Return the random code
return $random_code;
}
// Call the function to generate a random code
$random = make_random_code();
?>
"I wasn't quite sure what to think. Why is '$salt' named that way... at a stretch, I could understand 'seed'; but 'salt'? Why seed ('salt'?) the randomizer with (double)microtime()*1000000, when microtime() already returns a string that looks like '0.53138500 1203062920'? Why srand - which is basically deprecated as of PHP4, and accepts an int as an argument, not a double. And why, oh why use a loop?
"I decided against any further exploration or even trying to figure out why my predecessors chose such an elaborate routine to generate a random string to prevent a browser from cacheing. I just quitely replaced it with content.php?rnd=<?php echo time(); ?>.