Ad space (banner)
๐Ÿ˜PHP Lessons
Lesson 52 / 68

File Reading and Writing Basics

In this lesson you will learn the basics of reading and writing files with file_put_contents and file_get_contents. This is for anyone searching for "PHP file read write".

file_put_contents() writes a string to a file and file_get_contents() reads one back. Saving configuration files and logs makes this a basic operation you will use often. Completing a file operation in a single function call is characteristically PHP.

The sample code writes two lines of text with file_put_contents("memo.txt", "Hello\nThis is line 2") and reads them back with file_get_contents("memo.txt"). Notice how these two functions alone cover basic file work.

A common stumbling block for beginners is writing code that ignores the possibility of failure. A missing file makes these functions return false, so checking the return value is the safe habit. In practice you must always allow for failures such as writing to a location you lack permission for.

Checking the return value for the missing-file case makes your file handling far more robust. Recording logs and managing configuration files are daily work in real PHP applications.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run PHP directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)