PHP Files

In this tutorial you will learn about the PHP Files and its application with practical example.

PHP has the built in support and wide range of functions to perform file IO operations like –

  • Opening a file
  • Reading a file
  • Writing a file
  • Closing a file

Reading a file in PHP

fopen() function is used to open a file. It requires two parameters first the file name and then mode in which to open.

r Read only. Starts at the beginning of the file
r+ Read/Write. Starts at the beginning of the file
w Write only. Opens and clears the contents of file; or creates a new file if it doesn’t exist
w+ Read/Write. Opens and clears the contents of file; or creates a new file if it doesn’t exist
a Append. Opens and writes to the end of the file or creates a new file if it doesn’t exist
a+ Read/Append. Preserves file content by writing to the end of the file
x Write only. Creates a new file. Returns FALSE and an error if file already exists
x+ Read/Write. Creates a new file. Returns FALSE and an error if file already exists

So here are the steps required to read a file with PHP.

  • Open a file using fopen() function.
  • Get the file’s length using filesize() function.
  • Read the file’s content using fread() function.
  • Close the file with fclose() function.

Example:

 

Recommended:-  PHP Regular Expression

Writing a file in PHP

A new file can be created or text can be appended to an existing file using the PHP fwrite() function. This function requires two arguments specifying a file pointer and the string of data that is to be written.

Example:

 

In this tutorial we have learn about the PHP Files and its application with practical example. I hope you will like this tutorial.