PHP File

In the previous lesson we learned how to enable our users to upload files to the server. In this lesson, we'll learn how to work with files on the server.

Reading a File

The following code can be used to read a file.

Here's an explanation of what's happening:

  1. Before you read a file you need to open it. We're using PHP's fopen() function and providing it with two parameters: the file name and the mode in which it should be opened.
  2. We then loop through the file using PHP's feof() function. This checks for the end of the file. Our loop specifies that, while the end of file has not been reached, process the code inside the loop.
  3. The code inside the loop uses PHP's fgets() function. This function reads the file line by line. We need to put our own break otherwise each line would end up on the same line.
  4. Finally, we close the file using PHP's fclose() function, passing the opened file as a parameter.

Writing to a File

The following code can be used to write to a file.

Here's an explanation of what's happening:

  1. Again, we use PHP's fopen() function and supply it with two parameters: the file name and the mode in which it should be opened.
  2. We then use PHP's fwrite() function to write to the file. We supply two parameters: the opened file, and the text to go inside the file.
  3. Finally, we close the file using PHP's fclose() function, passing the opened file as a parameter.

Appending Data to a File

The previous code overwrites any content that might have been in the file. If you only want to add to the end of the existing data, you can simply change the mode from "w" (for "write") to "a" (for "append").

Deleting a File

To delete a file, you use PHP's unlink() function and provide it with the name/path of the file to delete.