0

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!

Community
  • 1
  • 1
Jingles177
  • 499
  • 2
  • 7
  • 16

2 Answers2

2

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

Iván
  • 21
  • 2
0

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.

hobbs
  • 223,387
  • 19
  • 210
  • 288
  • The implicit unlock doesn't happen any more since PHP-5.3.2. Furthermore this is not OP's issue. The implicit truncate of `fopen()` in mode `w` is causing the corruption. – Markus Malkusch Nov 20 '14 at 13:13
  • @MarkusMalkusch the implicit unlock *does* happen; it's just done by the OS instead of PHP doing an unnecessary and wrong `flock(..., LOCK_UN)` on its own. – hobbs Nov 20 '14 at 16:25
  • True, it does happen. But I still don't see how your answer fits OP's issue. – Markus Malkusch Nov 20 '14 at 17:19