faqts : Computers : Programming : Languages : PHP : Common Problems : Files

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

11 of 19 people (58%) answered Yes
Recently 4 of 10 people (40%) answered Yes

Entry

How can I write something at the beginning of a file without overwriting the rest of it?
How can I insert content in the middle of a file without overwriting the rest of it?

Jul 20th, 2004 01:12
Jens Clasen,


I had to answer these questions too often, so something in advance:
o The current versions of PHP have no possibilities whatsoever to edit
  a File as You can do in an editor like emacs or notepad.
o If You want to change a file without loosing the previous content,
  You have to buffer the old content, change it in the buffer and
  then You have to COMPLETELY rewrite the whole file.
For this purpose the following source might help You to understand
how this is done:
<?php
  # Function: file_insert_line()
  # ============================
  #
  # bool file_insert_line (string filename,
  #                        string new_entry
  #                        [, int position
  #                        [, int count]])
  #
  # Note:
  # o  If <position> is not specified, it is assumed to be 0.
  #    Further notice that <position> means the line before the new
  #    line will be inserted and that line-count starts at zero!
  # o  If <count> is not specified, it is assumed to be 1.
  # o  This function returns False on error.
  # o  All this could be done much shorter using array_fill(),
  #    which would not work with PHP3 and therefor was excluded
  function file_insert_line($file,$line,$position=0,$count=1){
    # checks if file exists, otherwhise it will be created
      if(file_exists($file))
        $buffer=file($file); # previous content >>> $buffer
      else
        $buffer=array();     # $buffer remains empty
    # different OS' use different line delimiters for their text-files,
    # therefor whe have to find out the right one..
      $delimiter=(preg_match("#\\\r\\\n#",$buffer[0]))?"\r\n":"\n";
    # inserting the new line into buffer...
      for($i=0;$i<count($buffer);$i++)
        if($i!=$position)
          $buffer2[]=$buffer[$i];
        else
          for($count;$count>0;$count--)
            $buffer2[]=$line.$delimiter;
    # rewriting file...
      $fp=@fopen($file,"w+");
      if(!$fp) return False; # return False on Error
      fputs($fp,implode("",$buffer2));
      fclose($fp);
    # return True on success
      return True;
  }
  # Function: file_update_line()
  # ============================
  #
  # bool file_update_line (string filename,
  #                        mixed update,
  #                        mixed where,
  #                        [,bool regex])
  #
  # Note:
  # o  If <regex> is not specified, it is assumed to be False,
  #    therefor <where> is taken as a line-number in this case
  # o  If <regex> is specified, <line> and <where> are taken as
  #    regular expressions. For more Info see:
  #    http://www.php.net/preg_replace
  # o  This function returns False on error.
  function file_update_line($file,$line,$where, $regex=False){
    # checks if file exists, otherwhise it will be created
      if(file_exists($file))
        $buffer=file($file); # previous content >>> $buffer
      else
        $buffer=array();     # $buffer remains empty
    # different OS' use different line delimiters for their text-files,
    # therefor whe have to find out the right one..
      $delimiter=(preg_match("#\\\r\\\n#",$buffer[0]))?"\r\n":"\n";
    # update
      if($regex){ # Using regular expressions ???
        for($i=0;$i<count($buffer);$i++){ # walk the hole file
          $buffer[$i]=preg_replace($where,$line,$buffer[$i]);
        }
      } else $buffer[$where]=$line.$delimiter; 
    # rewriting file...
      $fp=@fopen($file,"w+");
      if(!is_resource($fp)) return False; # return False on Error
      fputs($fp,implode("",$buffer));
      fclose($fp);
    # return True on success
      return True;
  }
?>