fopen question

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
KakCAT
Forum Newbie
Posts: 1
Joined: Tue Jul 24, 2012 1:44 pm

fopen question

Post by KakCAT »

Hi!

I'm trying to cache a file which will be accessed thousands of times in the next 20 seconds (online records of a game). I wanted to use semaphores but once I had everything working, the web server had them disabled.

my code now (using fopen) looks like this:

// (1) open cached file
$f=fopen ($fn,"rb");
if ($f!=FALSE) outputCachedFile();


// (2) create new file
$f=fopen ($fn,"xb");
if ($f==FALSE) { file is being created, wait a little bit and then load with outputCachedFile }


// (3) create data, then write it and close $f


When I run this code concurrently, the first thread creates the file at (2) , but the second one calls fopen at (1) and waits for (2) in the other thread to finish.

That's absolutely perfect for me, but I'd like to know if I can expect the same behaviour for every php version (>5) or this is just a coincidence of my server and this PHP version.

Thanks a lot!
Kak
User avatar
tr0gd0rr
Forum Contributor
Posts: 305
Joined: Thu May 11, 2006 8:58 pm
Location: Utah, USA

Re: fopen question

Post by tr0gd0rr »

I would think fopen locks files like that by definition. In my actual experience, file locking using fopen works the same on Apache with PHP 5.0 through 5.3 for OSX, Windows, Linux. Other servers like IIS and nginx probably work the same way too.
Post Reply