How PHP handles files
Shobhan Challa on 2002 May 13
    

This article discusses the various file handling options availabe in PHP and how we can implement them

.

Overview

We begin with a look at the basic read operations, and progress through to the more complex write operations.

PHP's filesystem functions provide a fairly broad range of functionality. All the standard functions that programmers expect are included:



    opening, reading, and writing files;
    querying the filesystem;
    changing permissions; copying and deleting files;
    ...and more



Many of these functions have been transparently extended to work with HTTP and FTP resources, allowing easy reading of remote files.

We'll look at some of the file functions like (fopen(), fread(), fwrite(), fileperms()) for checking permissions, reading, writing..etc.

Reading the contents of the file involves three steps:

1) Open the file, store the return value in a file pointer
2) Read the file
3) Close the file



fopen()

The syntax of fopen() is fopen(filename, mode), here filename is may be a URL of a file on ur local system.

fopen() opens a file on the current system and positions the file pointer at the beginning of the file. If PHP has been configured to be URL-aware, prefixing the filename with either http:// or ftp:// opens a connection to the specified URL and returns the contents of the specified file.

The mode strings can be one of the following:




    Mode String    Function
    r        Read only
    r+        Read and write, preserves file contents
            (overwrites existing content on write operations)
    w        Open and truncate existing file to zero length
            or create a new file
    w+        Open for read and write, truncate existing file
            to zero length or create a new file
    a        Read only, create new file or append to end of
            existing file
    a+        Read and write, create new file or append to end
            of existing file



A URL can be opened like this:


<?php

    
// conect to handle a file
    
$file_handler fopen("http://www.php.net/""r");

    
/* to open a local file use this instead
        $file_handler = fopen("data.txt", "r");
    */

    // read the contents
    
$contents fread($file_handlerfilesize($file));

    
// close the file
    
fclose($file_handler);

    
// print the contents on your page
    
echo $contents;


?>



Now we have a $file_handler variable, we can use it to quickly and easily reference our file. The fread() function is one of several that use a file pointer.

The second parameter indicates how many bytes of the file we want to read If the whole file is needed, then the filesize() function can be used, as this returns the exact number of bytes the file specified as the parameter takes.

The bytes argument allows for a set number of bytes to be read, although reading stops if EOF is reached first. The function is binary-safe, allowing it to safely read binary data (such as images or program executables), as well as character data. The data read is returned as a string.

Finally, we close the file pointer using fclose(). Now the file contents are stored in a $fcontents varibale. We print the contents using the familiar echo() function.



Here there are some file read functions for various situations:

file()

file() reads the contents of a file into an array, with each line of the file being an element of the array. Newline characters remain attached to the strings. The syntax is array file(filename).

Usage:


<?php

    $file_array 
file("test.txt");

    for ( 
$i 0$i count($file_array); $i++ ) {
        echo 
$file_array[$i];
    }
    

?>


readfile()

readfile() function outputs the contents of a file directly to standard output. This can also open a URL.

Usage:


<?php
    
//open a local file
    
$file "data.txt";

    
// open a URL
    
$http_file "http:www.php.net/projects.php";

    echo 
readfile($file);
    echo 
readfile($http_file);        
    

?>


file permissions

In the UNIX world our PHP script must have permissions to read, write and execute files. In the above case if we want to read the data.txt file we need to make sure that we have read permission on that file. Here's a chart of permission settings:



    4  read
    2  write
    1  execute



Typically a file permission looks like this -rw-rw-r--, here the first is the Owner who has read write permissions, second is theg Group who also has read and write permissions, and the third one is Everyone else who have only read permission. So, make sure you have the necessary permissions before reading, writing or deleting files using PHP.

A handy function to retrieve file permissions is fileperms(). The syntax of this function is int fileperms(filename).


<?php

    $file_perm 
fileperms("data.txt");
    echo (
$file_perm);


?>


Note: This function doesn't produce meaningful results on systems not supporting UNIX-like filesystems.



Writing to a file

We can write to a file using fputs or fwrite functions. fputs() writes the data given in data to the specified file. The optional bytes argument denotes the maximum number of bytes to be written to the file. fputs() can write both binary data (such as an image), and character data.

Here's how we use it:


<?php

    $string 
"Voila, it's weekend heren";
    
$file "test.txt";

    
$file_handler fopen($file"w");
    
fputs($file_handler$string);
    
fclose($file_handler);

    echo 
"Wrote "$string" to file $file";


?>


Here before creating the test.txt the script attempt to look for the file, if the file exists it writes the string while if theres no such file the script creates a new file with its default permissions.


File tests

There are many handy functions for testing if a particular file is readable(), writable(), filetype(), etc. Heres a little intro of some of these functions:

is_readable()

is_readable() checks wether a specified file is readable by PHP. The function returns TRUE if redable and FALSE otherwise.


<?php

    $file 
"data.txt";

    if(
is_readable($file)) {
        
// open and write to file
    
}
    else {
        echo 
"Cannot write to file <b>$file</b>.";
    }


?>


is_writable()

is_writable() function is similar to is_readable(), but it checks instead wether a file is writable or not.

There are also a series of convenience functions like fgetcsv(), which parses CSV-format data while reading it from a file, functions to copy, delete, rename and do all types of work with files.

I think I've covered pretty much on file operations by now, and it should now be OK to leave the exploration of other functions up to you.

Shobhan Challa
Web Developer
Tentatively planning to Open Soon! (no dates ...) // Doing heavy development now...