Archive for August, 2008

This story made a few wince when I told it..

Wednesday, August 27th, 2008

So a while back, at work over lunch, the conversation turned to dentistry for some reason, and that reminded me of something that happened to me when I was back in the Army.  After my tour in Germany, I finished things up at Ft. Polk Louisiana (where when everyone got their orders from my unit shutting down- the only one that said anything was Sgt. Dobbs, and he said ‘well son, the only thing I can say is I was there, and I got bit on the neck by a brown recluse‘). Nice.

(more…)

Solid random number generator function for PHP

Tuesday, August 26th, 2008

So, PHP’s random number generation is pretty weak- it uses the rand() function which is positively atrocious for anything more than playing a guessing game. So, I wrote the following to give me something a bit better- maybe someone else can use it too (and it’s fast). The good thing is if it can’t read /dev/urandom, it’ll fall back to the mediocre mt_rand() function:

public function random($min = 0, $max = 0) {
   $response = 0;

   if (($fd = fopen("/dev/urandom", "rb")) !== FALSE) {
      # 32 bits of data
      $read_len = 4;

      # MD5 is probably not needed, but whatever.
      $random = md5(fread($fd, $read_len), TRUE);
      fclose($fd);

      $val = 0;
      for($i = $read_len - 1; $i >= 0; $i--) {
         $ch = substr($random, $i, 1);
         $val = ($val << 8 ) | ord($ch);
      }

      $response = ($val % ($max - $min + 1)) + $min;
   } else
      $response = mt_rand($min, $max);

   return $response;
}