2

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.";
}
?>
PaulELI
  • 446
  • 5
  • 15
  • 7
    Why not use a MySQL database? Easier and would handle 200 simultaneous requests of that nature pretty quickly and efficiently. – Tim Withers Mar 15 '12 at 21:36
  • 3
    Writing to files in this manner can indeed be error prone. You might consider something such as SQLite if you can't use a regular database. That said, without some more information on expected traffic and what the actual goal is then it's hard to say. – Cfreak Mar 15 '12 at 21:36
  • Or SQLite, if you want to keep it simple. At all: Use a database to save data – KingCrunch Mar 15 '12 at 21:37
  • Yes, please use a database solution. It will put everyone's worries at ease (and you can do so much more with them down the road). – webbiedave Mar 15 '12 at 21:50
  • Thanks all. I usually go the MySQL route. I will just write a script to export out the db info to a csv file so they can have a file to import into excel. – PaulELI Mar 16 '12 at 06:08

1 Answers1

1

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

dqhendricks
  • 17,461
  • 10
  • 44
  • 80
  • I know how to write to a DB, I usually go that route. I was just trying something new. I will go that route. Thanks for the great replies all. – PaulELI Mar 16 '12 at 06:07