Re: How to "synchronize" file write accesses



Daniel Molina Wegener wrote:
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

Netx <user72cut-it-out@xxxxxx>
on Tuesday 13 January 2009 20:23
wrote in comp.lang.php:


My .php script checks if the "_copper.txt" file is not older than
1h.
If it is older than the content of "_copper.txt" is
imported/updated from the other web page.
Then the content of "_copper.txt" file is displayed.

So in need of "update" I have the following fragment :
$myFile = '_copper.txt';
$fh = fopen($myFile, 'w') or die('can\'t open _copper.txt');
//--CODE TO IMPORT COPPER PRICE FROM WWW
//(...)
fwrite($fh,$copper1);
fclose($fh);

However I am afraid what will happen if two persons request the
page and two "threads" fire fopen() for write? I can get over
problems
with one badly processed request, but I am afraid that
"_copper.txt" file may be damaged what will lead to all
subsequent requests badly displaying copper price.
How would you suggest to correct it and if possible without
database?

Mark


function getCopper()
{
$filename = '_copper.txt';
$filemtime = filemtime($filename);
$currenttime = mktime();
$diff = $currenttime - $filemtime;
//seconds to refresh:
if ($diff > 3600) {
getCopperReally();
}
$fh = fopen($filename,'r') or die ('can\'t open
_copper.txt');
$theData = fread($fh, filesize($filename));
fclose($fh);
print ($theData);
}

function getCopperReally()
{
$myFile = '_copper.txt';
$fh = fopen($myFile, 'w') or die('can\'t open _copper.txt');
$result=get_web_page('www-address-goes-here');

//process the page to get copper price into $copper1
//(it works)

fwrite($fh,$copper1);
fclose($fh);
}

Did you tried using file_get_contents() and file_put_contents()?

Best regards,

Doesn't solve the problem with multiple opens for write.

P.S. Your sig separator is broken.

--
==================
Remove the "x" from my email address
Jerry Stuckle
JDS Computer Training Corp.
jstucklex@xxxxxxxxxxxxx
==================
.