PHP Function to Open, Edit and Save (NOT APPEND!!) File

PHP Code to Open a File, Change the Contents of the File and then Resave to File

Home Short:

The php code below allows you to do the following:

  1. Check if a file exists AND is readable not corrupt.
  2. If the file does not exist or is damaged, create the new file.
  3. Open the file that was just checked and confirmed as existing and readable in step #1 OR the newly created file in step #2
  4. Make changes to the contents of the file.
  5. Resave the file with its new changes.

If you are new to php file handling, the different modes of opening a file r, r+. w. w+, a, a+, ... can be confusing and make it more difficult that it should be to perform a simple edit of an existing file.

The trick lies in ...

  1. opening the file in read only mode, placing the contents of the file into a variable.
  2. Making changes/edits to the variable.
  3. Resaving the file by, strangely enough, opening the file again in write mode.
  4. Save the contents of the variable, with the original file with the edits performed, back to file.
S
H
A
R
E