All TalkersCode Topics

Follow TalkersCode On Social Media

devloprr.com - A Social Media Network for developers Join Now ➔

PHP File Input Output

PHP File Input Output in this chapter we will discuss how to open, read, write and close the files.



Open The File

To open the file PHP use fopen() function it takes two parameters first is name of the while and other is the mode of the file read, write etc.


fopen() has many modes like..


  • r is used to open the file to read only. Places the file pointer at the beginning of the file.

  • r+ is used to open the file to read and write both. Places the file pointer at the beginning of the file.

  • w is used to open the file to write the file. If files does not exist then it attemts to create a file. Places the file pointer at the beginning of the file.

  • w+ is used to open the file to write and read both. If files does not exist then it attemts to create a file. Places the file pointer at the beginning of the file.

  • a is used to open the file to write only. If files does not exist then it attemts to create a file. Places the file pointer at the end of the file.

  • a+ is used to open the file to read and write only. If files does not exist then it attemts to create a file. Places the file pointer at the end of the file.

  • x is used to open the file to create new file for write. If files does not exist then it attemts to create a file.

  • x+ is used to open the file to create new file for read and write. If files does not exist then it attemts to create a file.



Reading File

To read file PHP use fopen() to open the file then use fread() function it takes two parameters first is name of the file and other is the number of bytes you want to read.


fread($file,filesize("demo.txt"));

filesize() is used to get the length of the file.




Writing File

To write a file PHP use fopen() to open the file then use fwrite() function it takes two parameters first is name of the file and other is the string used to write.


fwrite($file,This is just sample text);



Closing File

To close a file PHP use fclose() function it takes only one parameter name of the file.


fclose(demo.txt);
❮ PrevNext ❯