并发文件写入PHP

时间:2012-03-15 21:33:47

标签: php fputcsv

我有一个偏执客户的项目......如果有超过200人同时使用该网站,他担心该网站会崩溃。

我的脚本看起来会收集数据吗?或者该文件会给用户带来错误吗?

<?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.";
}
?>

1 个答案:

答案 0 :(得分:1)

使用MySQL等数据库存储数据。它将处理更高的负载。

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