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
The php code below allows you to do the following:
- Check if a file exists AND is readable not corrupt.
- If the file does not exist or is damaged, create the new file.
- Open the file that was just checked and confirmed as existing and readable in step #1 OR the newly created file in step #2
- Make changes to the contents of the file.
- 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 ...
- opening the file in read only mode, placing the contents of the file into a variable.
- Making changes/edits to the variable.
- Resaving the file by, strangely enough, opening the file again in write mode.
- Save the contents of the variable, with the original file with the edits performed, back to file.