PHP
fwrite() and fread()
Learn to write with fwrite() and read with fread().
Writing to a handle with fwrite()
After opening a file with fopen(), you write to the handle using fwrite(). The function takes the handle and the string to write.
For example, fwrite($handle, 'Hello'); writes 'Hello' to the file pointed to by $handle. The function returns the number of bytes written.
For the written data to reach disk you need to close the handle. We will cover fclose in detail in the next lesson; for now just know that you call fclose($handle) after fwrite.
Reading from a handle with fread()
To read from a handle you use the fread() function. It takes the handle and the number of bytes to read.
For example, $data = fread($handle, 5); reads 5 bytes from $handle and stores them in $data. The cursor advances by the amount read; the next fread continues where the previous one stopped.
You cannot read straight from a handle you opened in write mode; you first need to close and reopen the file, or flush the write with fclose. In this lesson we will fclose after fwrite and then reopen the file in 'r' mode.
Exercise Write and read back
Open note.txt with fopen() in 'w' mode and assign the handle to $wr. Use fwrite() to write 'Hello' and close with fclose($wr). Then open the file in 'r' mode, assign the handle to $rd, read 5 bytes with fread() into $data and print it with echo.
Show example solution
Write fwrite($wr, 'Hello'); fclose($wr);. Then $data = fread($rd, 5); echo $data;.
Example solution:
<?php
// Open in write mode
$wr = fopen(__DIR__ . '/note.txt', 'w');
// Write 'Hello' and close
fwrite($wr, 'Hello');
fclose($wr);
// Open in read mode
$rd = fopen(__DIR__ . '/note.txt', 'r');
// Read 5 bytes
$data = fread($rd, 5);
// Print it
echo $data;
Test yourself
-
What does fwrite($handle, 'abc') return on success?
- true or false
- The number of bytes written (3)
- The written string itself
- The file handle
Show answer
The number of bytes written (3) — Correct. fwrite() returns the number of bytes written; 'abc' is 3 bytes so it returns 3.
-
Complete the fwrite call
$bytes = fwrite($handle, ____);
Show answer
$bytes = fwrite($handle, 'Hello');
-
Match fwrite and fread concepts
- fwrite()
- Writes to a handle
- fread()
- Reads from a handle
- Second argument
- String or byte count
- Return value
- Is the byte count
Next lesson: Closing files with fclose()