Concept Flow - Reading files (fread, fgets, file)
Open file with fopen()
Choose reading method
fread()
Read bytes
Process data
Close file with fclose()
Open a file, pick a reading method (fread, fgets, or file), read data, then close the file.
<?php $handle = fopen('test.txt', 'r'); $content = fread($handle, 10); fclose($handle); echo $content; ?>
| Step | Action | Function Call | Result/Value | Notes |
|---|---|---|---|---|
| 1 | Open file for reading | $handle = fopen('test.txt', 'r') | Resource handle | File opened successfully |
| 2 | Read 10 bytes from file | $content = fread($handle, 10) | 'Hello Worl' | Reads first 10 bytes from file |
| 3 | Close the file | fclose($handle) | true | File closed |
| 4 | Output content | echo $content | Hello Worl | Prints the read string |
| Variable | Start | After fopen | After fread | After fclose | Final |
|---|---|---|---|---|---|
| $handle | null | resource | resource | resource | resource |
| $content | null | null | 'Hello Worl' | 'Hello Worl' | 'Hello Worl' |
Open a file with fopen('filename', 'r')
Read data using fread(handle, bytes), fgets(handle), or file('filename')
Process the data as needed
Close the file with fclose(handle)
Use fread for fixed bytes, fgets for lines, file() for all lines at once