PHP 5.x syncronized file access (no database)

让人想犯罪 __ 提交于 2019-12-05 07:28:24

You could try php's variant of flock (http://www.php.net/flock)

I would envision something similar to (this assumes that the file /tmp/counter.txt already exists and has a counter in the file):

<?php

$fp = fopen("/tmp/counter.txt", "r+");

echo "Attempt to lock\n";
if (flock($fp, LOCK_EX)) {
  echo "Locked\n";
  // Read current value of the counter and increment
  $cntr = fread($fp, 80);
  $cntr = intval($cntr) + 1;

  // Pause to prove that race condition doesn't exist
  sleep(5);

  // Write new value to the file
  ftruncate($fp, 0);
  fseek($fp, 0, SEEK_SET);
  fwrite($fp, $cntr);
  flock($fp, LOCK_UN); // release the lock
  fclose($fp);
}

?>

PHP's flock() function is the route to go. However, you have to make sure that all accesses to the file are protected by a call to flock() first. PHP won't check if the file is locked unless you explicitly make the call to do so.

The concept is virtually identical as with mutexes (protecting shared resources, et al), but it's important enough to bear special emphasis.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!