Jingles177
Jingles177

Reputation: 539

PHP Flock Writing to Open File

I have a php script that logs ads(banners) for a website and stores them to a .dat file. Inside this file an ID, URL, an other important information is saved. The problem I am having is that there are at any given time 4 ads on the page and so the .dat file is often corrupted when the php script attempts to write to it while it is open.
I checked and tried this solution however it did not help me: PHP Simultaneous file access / flock() issue

The function I am using at the moment looks like this:

function writeads(){
    global $bannerAdsPath, $ads, $bannerAds;
    $data = fopen($bannerAdsPath, 'w') or die();
    flock($data, 2) or die();
    fputs($data, @join("\n", $ads)."\n");
    while (list ($key, $val) = each ($bannerAds)) {
        if (($key != '') && ($val != '')) {
            fputs($data, $key.'='.$val."\n");
        }
    }
    flock($data, 3);
    fclose($data);
    reset($bannerAds);
}

Any help would be appreciated as I have been scratching my head over this for a while. Side bit of information, the client did not want to have their code rewritten to use a Database instead of a file so that option is out.

Thanks!

Upvotes: 0

Views: 290

Answers (2)

Iván
Iván

Reputation: 21

fopen with 'w' truncates the file before you have the option of flocking it.

Upvotes: 2

hobbs
hobbs

Reputation: 240531

You almost never want to use flock to unlock a file; just use fclose; the file will be unlocked when the handle is closed, and that way you know that no buffered writes will happen after you unlock.

Upvotes: 0

Related Questions