2
我有一個偏執的客戶端項目......他擔心如果超過200人同時使用該站點,網站將崩潰。併發文件寫入PHP
我的腳本看起來好像會收集數據嗎?或者該文件會給用戶錯誤?
<?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.";
}
?>
爲什麼不使用MySQL數據庫?更容易,並且可以快速高效地處理200個同時請求。 – 2012-03-15 21:36:01
以這種方式寫入文件確實可能容易出錯。如果你不能使用常規數據庫,你可能會考慮諸如SQLite之類的東西。這就是說,沒有關於預期交通的更多信息以及實際目標是什麼,那麼很難說。 – Cfreak 2012-03-15 21:36:33
或SQLite,如果你想保持簡單。完全:使用數據庫保存數據 – KingCrunch 2012-03-15 21:37:33