PHP fopen() – opening, creating a file

PHP fopen() function is used for opening a file or url in PHP. It can also be used for creating a file in PHP.We can use two parameters with this function. First parameter is for specifying the file name and second parameter is for specifying the mode for opening that file.

Syntax of the fopen() function is

$file=fopen(“file name”,”mode”);

for ex:

$file=fopen(“syam.txt”,”r”);

See the different opening modes used with fopen()

  • r : Open for read only, Start from the beginning of file
  • r+ : open for read and write , start from the beginning of file
  • w : Open for write only, if the file exists all the data will be removed and start from the beginning, if the file not exist – it will create the new file
  • w+ : Open for write and read, if the file exists all the data will be removed and start from the beginning, if the file not exist – it will create the new file
  • a : Open for write only , mainly for append operation, will point to the end of file , will create a new file if file not exist
  • a+ : Open for read and write, will point to the end of file , will create a new file if file not exist
  • x : create and open for write only , starts from the beginning of file, if the file exist E_WARNING error will occur, if the file does not exist it will create a new file
  • x+ : create and open for read and write, starts from the beginning of file, if the file exist E_WARNING error will occur, if the file does not exist it will create a new file

From this we can see that following modes are used for creating a file in PHP

  • a
  • a+
  • w
  • w+
  • x
  • x+
Share
Share
Share