We also use fopen() to open existing files as well.

The function fopen() takes in two arguments, the filename and the mode to either open or create a file.

  • $filename - the name of the file. This may also include the absolute path where you want to create the file. Example, "/www/myapp/myfile.txt".
  • $mode - mode is used to specify how you want to create the file. For example, you can set the mode to create for read only, or create a file for read and write. Below is the list of possible modes you can use.

PHP file fopen create modes

'w' Open for writing only; place the file pointer at the beginning of the file and truncate the file to zero length. If the file does not exist, it attempt to create it.
'w+' Open for reading and writing; place the file pointer at the beginning of the file and truncate the file to zero length. If the file does not exist, attempt to create it.
'a' Open for writing only; place the file pointer at the end of the file. If the file does not exist, attempt to create it.
'a+' Open for reading and writing; place the file pointer at the end of the file. If the file does not exist, attempt to create it.

There are additional ways to open a file.

  • Read/Write: 'r+'

Opens a file so that it can be read from and written to. The file pointer is at the beginning of the file.

  • Write/Read: 'w+'

This is exactly the same as r+, except that it deletes all information in the file when the file is opened.

  • Append: 'a+'

This is exactly the same as r+, except that the file pointer is at the end of the file.

Related Posts by Categories