How to Open a File in PHP

By Techwalla Contributor

Use the "fopen" function to open files in PHP. You must pass the name of the file and the "open" option. Use the "r" option to open an existing file as read-only. When a file is opened as read-only, you start at the beginning of the file and cannot write to it at all. Use the 'w' option, to truncate the file and open it as write-only. This option erases the contents of the file, places the pointer in the beginning of the file and starts writing from there.

Open a File in PHP as Read-Only

Step 1

Set a variable to the file you want to use: $myFile = 'simpleFile.txt';

Step 2

Open a file, saving the reference in the "fh" variable: $fh = fopen($myFile, 'r') or die('Can't open file');Change the "r" to a "w" to open the file as write-only, rather than read-only.

Step 3

Close the file to prevent resource leaks: fclose($fh);

Tips & Warnings

  • PHP also contains other advanced options for opening files. Visit the W3School's PHP File Handling page for a full list and more examples.
  • Create a back-up copy of the files you plan to open.

References & Resources