File Reading and Writing Functions

Started by chinmay.sahoo, 12-24-2015, 00:40:20

Previous topic - Next topic

chinmay.sahooTopic starter

This is a supremely useful set of functions, particularly for data sets too small or scattered to merit the use of a database. File reading is pretty safe unless you keep unencrypted passwords lying around, but file writing can be quite unsafe.

Remember that although the Web server (and client-side languages such as JavaScript) can only act on files located under the document root, PHP can access files at any location in the file system—including those above or entirely outside the Web server document root—as long as the file permissions and include_path are set correctly. For instance, if your Web server document root is located at /usr/local/apache/htdocs, Apache will be able to serve only files from this directory and its subdirectories, but PHP can open, read, and write to files in /usr/local, /home/php, /export/home/httpd, or any other directory that you make readable and includable by the PHP and/or Web server user.

A file manipulation session might involve the following steps:

1. Open the file for read/write.
2. Read in the file.
3. Close the file (may happen later).
4. Perform operations on the file contents.
5. Write results out

Each step has a corresponding PHP filesystem function.

This archetypal example illustrates some subtleties of the syntax for manipulating file contents:

Quote$fd = fopen($filename, "r+")
or die("Can't open file $filename");
$fstring = fread($fd, filesize($filename));
$fout = fwrite($fd, $fstring);
fclose($fd);