Search code examples
phpfputcsv

Concurrent File Writes PHP


I have a project with a paranoid client... He is worried the site is going to crash if more than 200 people are using the site at the same time.

Does my script look like it will collect the data okay? Or will the file give users errors?

<?php
if($_POST['name'] && $_POST['email']) {
    //file name var
    $fileName = "mycsvfile.csv";

    //grab from form
    $name = $_POST['name'];
    $email = $_POST['email'];

    //date
    date_default_timezone_set("America/Los_Angeles");
    $today = date("F j, Y, g:i a");

    //set the data we need into an array
    $list = array (
        array($today, $name, $email)
    );

    // waiting until file will be locked for writing (1000 milliseconds as timeout)
    if ($fp = fopen($fileName, 'a')) {
      $startTime = microtime();
      do {
        $canWrite = flock($fp, LOCK_EX);
        // If lock not obtained sleep for 0 - 100 milliseconds, to avoid collision and CPU load
        if(!$canWrite) usleep(round(rand(0, 100)*1000));
      } while ((!$canWrite)and((microtime()-$startTime) < 1000));

      //file was locked so now we can store information
      if ($canWrite) {
        foreach ($list as $fields) {
            fputcsv($fp, $fields);
        }
      }
      fclose($fp);
    }

    //Send them somewhere...
    header( 'Location: http://alandfarfaraway' ) ;

}else{
    echo "There was an error with your name and email address.";
}
?>

Solution

  • Use a database such as MySQL to store your data. It will handle a much higher load.

    http://php.net/manual/en/book.mysql.php