Congratulations! You now know all about file handling in PHP. Here’s a recap of what you’ve learned:
fopenwith the correct mode to access a file for reading, writing, or appending.
- Close any files you’re not actively using with
- Read files with
- Write files with
- Retrieve information about files with operations like
- 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.
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.
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.
Create a new variable,
$to_do_size, and set it to the size of to-do.txt in bytes.
$to_do_size you just found, print the contents of to-do.txt to the console.
Finally, go ahead and close the file.