PHP File Handling
PHP File Handling
File handling is an important part of any web application. You often need to open and process a file for different tasks.
PHP has several built-in functions for creating, reading, uploading, and editing files.
The core functions for file handling is:
readfile()- reads a file and writes it to the output bufferfopen()- opens a file (gives you more options than thereadfile()function)fread()- reads from a filefgets()- reads a single line from a filefgetc()- reads a single character from a filefeof()- checks if the "end-of-file" (EOF) has been reachedfwrite()- writes to a filefclose()- closes an open fileunlink()- deletes a file
Note: Be careful when manipulating files!
You can do a lot of damage if you do something wrong. Common errors are: editing the wrong file, filling a hard-drive with garbage data, or deleting the content of a file by accident.
PHP readfile() Function
The readfile() function reads a file and writes its
contents to the output buffer (usually the browser).
Here, we have a text file named "webdictionary.txt", stored on the server, that looks like this:
AJAX = Asynchronous JavaScript and XML
CSS = Cascading Style Sheets
HTML = Hyper Text Markup Language
PHP = PHP Hypertext Preprocessor
SQL = Structured Query Language
SVG = Scalable Vector Graphics
XML = EXtensible Markup Language
Here is the PHP code to read the file, and write it to the output buffer:
The readfile() function is useful if all you want to do is open a file and
write its contents to the browser.
The next chapters will teach you more about PHP file handling.