PHP File Handling

PHP File Operations

PHP has a variety of functions available for creating, reading, uploading, and editing files.

Note:Please operate files with caution!

You must be very careful when operating files. If you make a mistake, it may cause very serious damage. Common errors include:

  • Edit Errors in the File
  • Hard Drive Filled with Garbage Data
  • Accidentally Deleted File Content

PHP readfile() Function

The readfile() function reads the file and writes it to the output buffer.

Suppose we have a text file named "webdictionary.txt" stored on the server, 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

The PHP code to read this file and write to the output stream is as follows (if read successfully, the readfile() function returns the number of bytes):

Example

<?php
echo readfile("webdictionary.txt");
?>

Run Instance

If all you want to do is open a file and read its content, the readfile() function is very useful.

The next section will explain more about file handling.

PHP Filesystem Reference Manual

For a complete PHP Filesystem reference manual, please visit the one provided by CodeW3C.com PHP Filesystem Reference Manual.