Hi!

Here is part two dealing with file handling. Let me start off with reading files and dealing with various methods of reading files. There are three functions we will deal with. file(), fopen() and file_get_contents(). Later on after describing each of the functions, ill give a few examples of how to combine the use of the them.

FILE

Lets start with file(). Using this function you will return the entire contents of the file into an array. Each line will be a separate instance in the array. Note that the newline character is still attached to the end of each line.

CODE
<?php

// Will return the entire contents of test.file into the array.
$f_arr = file('test.file'); #If test.file is in docroot.
$f_arr = file('/path/to/test.file'); #If test.file is in /path/to/.
print_r($f_arr); # Will print out the contents of the file line for line

?>


FOPEN

Now, lets to the fopen() and related functions. fopen() has two main input fields. The file and the opening mode. Here are the opening modes that you can specify:

'r' - Open for reading only; place the file pointer at the beginning of the file.
'r+' - Open for reading and writing; place the file pointer at the beginning of the file.
'w' - Open for writing only; place the file pointer at the beginning of the file and truncate the file to zero length. If the file does not exist, attempt to create it.
'w+' - Open for reading and writing; place the file pointer at the beginning of the file and truncate the file to zero length. If the file does not exist, attempt to create it.
'a' - Open for writing only; place the file pointer at the end of the file. If the file does not exist, attempt to create it.
'a+' - Open for reading and writing; place the file pointer at the end of the file. If the file does not exist, attempt to create it.
'x' - Create and open for writing only; place the file pointer at the beginning of the file. If the file already exists, the fopen() call will fail by returning FALSE and generating an error of level E_WARNING. If the file does not exist, attempt to create it. This is equivalent to specifying O_EXCL|O_CREAT flags for the underlying open(2) system call. This option is supported in PHP 4.3.2 and later, and only works for local files.
'x+' - Create and open for reading and writing; place the file pointer at the beginning of the file. If the file already exists, the fopen() call will fail by returning FALSE and generating an error of level E_WARNING. If the file does not exist, attempt to create it. This is equivalent to specifying O_EXCL|O_CREAT flags for the underlying open(2) system call. This option is supported in PHP 4.3.2 and later, and only works for local files.

The main ones that you will use are: r,w and a.

Here is a basic example of opening a file

CODE
<?php

// This will open the file in read-only mode
$fh = fopen('test.file','r');

// This will open the file in read and write mode (not blanking the file)
$fh = fopen('test.file','r+');

// This will open the file in write only mode (this will blank the file when opening)
$fh = fopen('test.file','w');

// This will open the file in read and write mode (this will blank the file when opening)
$fh = fopen('test.file','w+');

?>


Once you have an open file handler, there are two main commands that you can use to retrieve the data from the file: fgets() and fread(). I am going to use fread(), but fgets works in much the same manner. Fread() takes two input variables; The filehandler to read from and the length to read. A simple way to get the entire contents is to use filesize() to get the filesize and to request the entire file. If no second variable (length) is specified, it will default to 1k (1024).

CODE
<?php

// This will return the first 1024 bytes of the file into the string
$contents = fread($fh, 1024);

// This gets the same result as above:
$contents = fread($fh);

// This gets the entire file by setting the length to the entire size of the file
$contents = fread($fh, filesize('test.file'));

// Another method to get entire conents using a while loop
while (!feof($fh)) {
     $contents  .= fread($fh);
}
?>


Still making use of the fopen() class you can write to the file using the fwrite() line. Fwrite() takes two input variables: the filehandler and the line to write:

CODE
<?php

// The line that we will be writing
$line = 'Hello world!';

// This will write the line into the file with no newline
fwrite($fh, $line);

// This will write the line into the file with a newline character
fwrite($fh, $line."\n");

?>


Once finished using the fopen() class, you need to close it. To close a file, simply use fclose(). Fclose takes the filehandler as input:

CODE
<?php

// To close a file
fclose($fh);

?>



SIMPLE METHODS


Since php 4.3 (and greater) there are two simple commands to retrieve and write information into a file. They are file_get_contents() and file_put_contents(). Starting with file_get_contents it takes quite a few input variables but to keep this tutorial fairly simple, we wont deal with them since they arent used a lot. The main input is the filename that it will read. Note that this function only returns the contents of a file into a string.

CODE
<?php

// Gets the contents of test.file into a string.
$contents = file_get_contents('test.file');

?>


file_put_contents works in pretty much the same manner - it simply writes the data into the file. Its the same as calling fopen(), fwrite() and fclose() in sequence.

CODE
<?php

// Data to write
$data = "Hello!\n This file contains line breaks and cool stuff!!!\n";

// Write contents to the file
file_put_contents('test.file',$data);

?>


COMBINING THE METHODS

Here are a few examples of how to combine the methods to use the filehandler. This first example is used to find certain lines in a file and change them to something else, and then to write the file backout.

CODE
<?php

// Load the file into an array
$f_arr = file('test.file');

// Open that same file in write mode (blanking it)
$fh = fopen('test.file','w');

# Two methods could be used here - a for loop or a foreach loop. Below is a for loop

// Lets count the number of lines
$count = count($f_arr);

// Start the for loop
for($i=0; $i<$count; $i++)
{
     // Each line will now be $f_arr[$i]
     if(stristr($f_arr[$i],'Replace Me'))
     {
         $f_arr[$i] = 'Replaced Already!';
     }
    
     // Now write out the line into the blank file
     fwrite($fh,$f_arr[$i]); # Note that there is no newline character since i didnt trim() the line.
}


# Now for the other method - The foreach loop

foreach($file as $line)
{
     // In this example im going to trim() the line
     $line = trim($line);

     // Match $line now
     if(stristr($line,'Delete This line'))
     {
         continue; # Will move to the next line and not write this line to the file.
     }
     else if(stristr($line, 'Edit this lne'))
     {
         $line = 'Edit this line';
     }
    
     // Write out to file with a newline character
     fwrite($fh, $line."\n");
}


// Close the file
fclose($fh);


?>


SOME TIPS
- When in doubt, always trim() the line - It will remove all whitespace, newline, tab, normal spaces, null bytes or vertical tabs from the begining or end of the string.
- If you are having problems opening a file, add an "or die('Error')" after the fopen() line - it will die if it finds an error.
- Be sure to read up on the other file functions for some nice quick and easy pre written functions. a simple search for file on php.net will return lots of info
- Again, echo echo echo. oh use print_r as well, echo print as much as you can, it will always help with debugging smile.gif

Stay tuned for part 3 coming in the new year!