PHP Reading Files



Reading/Writing PHP Files


So far, we have been able to transport data from one file to another. However, if the user leaves our site, closes the browser, or we don't send all their information, we lose it. This data is called session data and is only temporary. To store data that will be permanent and ready for use at any time, we need to learn how to read and write files. The main function associated with file use is fopen(). The fopen function requires two parameters, file name/path and the mode. The mode is what you want to do with the file. Here are the different mode options: Typically, the code to create a file to write to looks like this:
$filename="../folderName/dataFile.txt";
$newfile=fopen($filename, "w") or die("Couldn't create file.");

The die() function prints your choice of message if the option fails. However, it will also give a long error message that you might not want users to see including the line on which the error occurred. To eliminate this error message and only display your message, alter the second line so that instead of fopen(...) it reads @fopen(...).

Also, remember that the w command will erase the file if it exists, so we may want to check and make sure that we are not writing over something important. This is accomplished using the following:
if(file_exists($filename))...

To write information to a file, we use the fwrite() function which takes a file name and the information to write to. So, in our previous example, we would write a string by the following code:
@fwrite($newfile, $string) or die("Couldn't write to file");


When writing separate records to a file, be sure to include some type of delimiter in your string like a newline character so that it is easy to separate and search. Similarly, to read information, we can use the fread() or fgets() method to read information from the file.
  1. fread() reads all of the file's information into a variable: $msg=fread($newfile, filesize($filename));
  2. fgets() can read a certain number of bytes or a newline character. So, using a while loop and the feof() function, we can read the code line by line:
    $inline=fgets($newfile, 4096);
    while(!feof($newfile))
    {
                echo "$inline";
                fgets($newfile, 4096);
    }
  3. There is also a fgetcsv() function which will allow you to read a line at a time, and separate the line into an array based on the delimiter that you used while writing. This is used as follows:
    $order = fgetcsv($newfile, 100, "\t");
    Just be sure that the number is greater than the biggest line you intend to read in your file.
**Whenever you finish working with a file, reading or writing, you should close the file using fclose($newfile).

Directories:



PHP also provides the ability to read/write/manipulate directories. Some of the functionality is described below: