File Handling in PHP 5

When we develop a web application using PHP, quite often we need to work with external files, like reading data from a file or maybe writing user data into file etc. So it's important to know how files are handled while working on any web application.


File Handling Operations

File handling starts with creating a file, reading its content, writing into a file to appending data into an existing file and finally closing the file. Php provides pre-defined functions for all these operations, so let's start by knowing these functions.

  1. Create a File: fopen()
  2. Open a File: fopen()
  3. Read a File: fread()
  4. Write to a File: fwrite()
  5. Append to a File: fwrite()
  6. Close a File: fclose()
  7. Delete a File: unlink()

You must be wondering that why we have specified same functions for multiple file operations, well, that is because just by changing one or more arguments, same function can be used to perform multiple operations on file.

Introduction to File Handling PHP

We will learn how to use these functions along with code examples in the next tutorials.


Uses of File in Applications

Following are some of the practical use cases where we need files in our web applications.

  • Oftenly data is stored in for of JSON files, amd Php code has to read the file and then display the data on web page.
  • In some simple applications, no database is used, rather data is stored in files.
  • In some web applications, you may have to prepare a file for user to download, in that case Php code will create a file, write data in it and then allow the user to download it.

The above usecases are just to show that very oftenly file handling is required.