note 34575 modified in function.fopen by danbrown
| From: | danbrown@php.net | Date: | Mon, 08 Jun 2009 23:44:33 +0000 |
| Subject: | note 34575 modified in function.fopen by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-156570@lists.php.net to get a copy of this message | ||
I offer the following script for updating a counter, using methods gleaned from various posts on
file operations...
<?php
$counter_file = 'somefile.txt';
clearstatcache();
ignore_user_abort(true); ## prevent refresh from aborting file operations and hosing file
$fh = fopen($counter_file, 'r+b'); ## use 'r+b' so file can be read and
written
if ($fh)
{
if (flock($fh, LOCK_EX)) ## don't do anything unless lock is successful
{
$count = fread($fh, filesize($counter_file));
rewind($fh);
$count++;
fwrite($fh, $count);
fflush($fh);
ftruncate($fh, ftell($fh)); ## better than truncating to 0 before writing, per
04-Mar-2003 comment below
flock($fh, LOCK_UN);
} else echo "Could not lock counter file '$counter_file'";
fclose($fh);
} else echo "Could not open counter file '$counter_file'";
ignore_user_abort(false); ## put things back to normal
echo "counter is at $count";
?>
--was--
I offer the following script for updating a counter, using methods gleaned from various posts on
file operations...
<?
$counter_file = 'somefile.txt';
clearstatcache();
ignore_user_abort(true); ## prevent refresh from aborting file operations and hosing file
$fh = fopen($counter_file, 'r+b'); ## use 'r+b' so file can be read and
written
if ($fh)
{
if (flock($fh, LOCK_EX)) ## don't do anything unless lock is successful
{
$count = fread($fh, filesize($counter_file));
rewind($fh);
$count++;
fwrite($fh, $count);
fflush($fh);
ftruncate($fh, ftell($fh)); ## better than truncating to 0 before writing, per
04-Mar-2003 comment below
flock($fh, LOCK_UN);
} else echo "Could not lock counter file '$counter_file'";
fclose($fh);
} else echo "Could not open counter file '$counter_file'";
ignore_user_abort(false); ## put things back to normal
echo "counter is at $count";
?>
http://php.net/manual/en/function.fopen.php