PHP and MySQL Programming/File Handling

From Wikibooks
Jump to navigation Jump to search

PHP uses a set of functions to deal with reading files from a computer hard-drive.

One of the basic functions is the fopen command. fopen opens a file. If successful, this returns a file handle. You can set a variable to use the file handle.

The file handle can be used with other commands to view or edit the file.


//Script 3-1 /* Small script to demonstrate the file handling commands */

$file_resource = fopen("file.txt","r"); $file_contents = "";

// Read the file line-by-line, until the end of the file is reached. while(!feof($file_resource)) {

      $file_contents .= fgets($file_handle); 



You'll notice two other functions present - feof() and fgets(). feof() accepts an file resource and determines whether the end of the file has been reached. fgets() also accepts a file resource, and moves forward by one line in that file resource by one file.

fwrite is another file handling function that you may encounter, which writes the requested data to the file. In order to use it, you will have to change the context that the file is opened in.

//Fragment 3-1 $file_resource = fopen("file.txt","w"); //Open the text file for writing only.

However, the use of these file handling functions is rather difficult. Fortunately this has been realized, and many of the file handling functions have been consolidated into just two. These are file_get_contents() and file_put_contents().


//Script 3-3 /*Simple example that does the same job as script 3-1*/

$file_contents = file_get_contents("file.txt");


Be wary however of writing files, you must append what you are writing to a buffer before you write it into the file, otherwise the file will be overwritten by what you want to add at the end.

//Script 3-4 /*Simple example that shows how to write a file using the modern file-handling functions*/

$file_contents = file_get_contents("file.txt"); $file_contents .= "This will be added to the end of the file.\n" \\ "\n" is the new line expression file_put_contents($file_contents);

Now, "file.txt" will have all the contents that it had before, plus the string "This will be added to the new file."