Learn

Congratulations! You now know all about file handling in PHP. Here’s a recap of what you’ve learned:

  • Use fopen with the correct mode to access a file for reading, writing, or appending.
  • Close any files you’re not actively using with fclose.
  • Read files with fread or file_get_contents.
  • Write files with fwrite or file_put_contents.
  • Retrieve information about files with operations like filesize and file_exists.
  • Find and diagnose errors by checking function return values, inspecting the console for error messages, and using file information functions.

To learn even more about file handling in PHP, try exploring the official PHP documentation for file system functions. In the meantime, let’s wrap things up with one more exercise.

Instructions

1.

We’ve started creating a to-do list in to-do.txt, but we’re not finished! To get started, use the file_put_contents function to append a new item to the file.

2.

Next, let’s prepare to read the file so we can view our entire to-do list. Create a variable, $to_do_file, and set it to the result of opening the file in read mode.

3.

Create a new variable, $to_do_size, and set it to the size of to-do.txt in bytes.

4.

Using the $to_do_size you just found, print the contents of to-do.txt to the console.

5.

Finally, go ahead and close the file.

Take this course for free

Mini Info Outline Icon
By signing up for Codecademy, you agree to Codecademy's Terms of Service & Privacy Policy.

Or sign up using:

Already have an account?