How do I use flock to read and write to files?

Discussion in 'PHP' started by Imozeb, Apr 10, 2010.

  1. #1
    I tried to use flock but it just ends up deleting the contents of my file. I want flock() to let other application read, but not write to this file.

    PHP code:
    
    $filename = '../text/file.txt';
    $fw = fopen($filename, "wrb");
    $fl = flock($fw, LOCK_SH);
    $data = 'hello';
    $numbytes = fwrite($fw, $data);
    flock($fw, LOCK_UN);
    
    Code (markup):

    Thanks.

    And mabye someone could tell me how to change a PHP array into a Javascript array?
     
    Imozeb, Apr 10, 2010 IP
  2. lukeg32

    lukeg32 Peon

    Messages:
    645
    Likes Received:
    19
    Best Answers:
    1
    Trophy Points:
    0
    #2
    You are opening the file with "write and read" access....... write will open at position 0 and truncate the file, hence why its overwriting. If you need to append to the file then you should be looking to use a+
     
    lukeg32, Apr 10, 2010 IP
  3. Imozeb

    Imozeb Peon

    Messages:
    666
    Likes Received:
    3
    Best Answers:
    0
    Trophy Points:
    0
    #3
    I'm confused. What do you mean by a+ I googled it and came up with nothing.
    Would this work to append my data?

    PHP code:
    $filename = '../text/file.txt';
    $fw = fopen($filename, "wrb");
    $fl = flock($fw, LOCK_SH);
    [COLOR="blue"]$data = fread($fw, filesize($filename))
    $data .= ' hello';[/COLOR]
    $numbytes = fwrite($fw, $data);
    flock($fw, LOCK_UN);
    Code (markup):
     
    Imozeb, Apr 11, 2010 IP
  4. lukeg32

    lukeg32 Peon

    Messages:
    645
    Likes Received:
    19
    Best Answers:
    1
    Trophy Points:
    0
    #4
    When you are opening the file here;

    $fw = fopen($filename, "wrb");
    PHP:
    You are opening with mode "wrb" - by opening a file for Write, it will truncate the file to 0 bytes; that is, remove all the data. You should open with mode a+ and not mode wr if you want to add onto the end of it.

    No - as the file will be truncated when opened (so it will be 0 bytes).
     
    Last edited: Apr 12, 2010
    lukeg32, Apr 12, 2010 IP
  5. Imozeb

    Imozeb Peon

    Messages:
    666
    Likes Received:
    3
    Best Answers:
    0
    Trophy Points:
    0
    #5
    Thanks lukeg32. Using a+b worked!
     
    Imozeb, Apr 12, 2010 IP