title: When does mod_php in apache seed the random number generator?
body: <p>I am using the php rand() function to generate coupon codes for my e commerce system.
  It worked fine for a while but now I am getting a lot of errors that the code is already in the system.</p>
  
  <p>This is the function I use:</p>
  
  <pre><code>function generateRandomString($length) {
      $characters = '0123456789abcdefghijklmnopqrstuvwxyz';
      $randomString = '';
      for ($i = 0; $i &lt; $length; $i++) {
          $randomString .= $characters[rand(0, strlen($characters) - 1)];
      }
      return $randomString;
  }   
  </code></pre>
  
  <p>And my codes are 32 characters long.</p>
  
  <p>I did a sample of ~150 tries and noticed that more than 50% of the generated codes where laready in the system.</p>
  
  <p>I have 4212 codes in the system. The odds of a 32 character random string with 36 different symbols producing a collision are basically zero, and I get 50% collisions.</p>
  
  <p>When I re-seeded the random number generator in my function by calling <code>srand();</code> I did not have any collisions any more.</p>
  
  <p>But on the man page of php it cleary says:</p>
  
  <blockquote>
    <p>Note: As of PHP 4.2.0, there is no need to seed the random number
    generator with srand() or mt_srand() as this is now done
    automatically.</p>
  </blockquote>
  
  <p>I am running php version <code>PHP 5.5.9</code></p>
  
  <p>So my thoughts where something like that seeding is done, but only once per webserver worker, and then when the process is forked, it is not reseeded or something like that.
  But that would be clearly a bug in apache...</p>
  
  <p>I am running php as apache modul in apache version <code>Apache/2.4.7 (Ubuntu)</code> and the <code>mpm_prefork_module</code> module</p>
  
  <p>So do I still need to call <code>srand()</code> at the top of every script dispite the manpages saying other wise, and why? Is it apaches fault or PHP's?</p>
  
  <p>And yes, I am aware that I should not use this function for this purpose, and I will update it to use cryptographically secure numbers. But I think this should not happen anyway and I am still interested in what is going on!</p>