Приглашаем посетить
Спорт (www.sport-data.ru)

Files

Table of Contents
Previous Next

Files

A file is a sequence of bytes stored persistently on a physical medium like a hard disk. Each file is uniquely identified by its absolute path. For example, C:\temp\textfile.txt on Windows platforms or /private/user/textfile on UNIX platforms.

On Windows, both the forward slash (/) and the backslash (\) can be used in file paths, whereas other operating systems use only the forward slash. As a good programming practice, you should define a global variable fileSeparator and use it for creating paths in your PHP programs. This is an extreme scenario, but, in some operating systems the forward slash (/) can be part of the filename.

Most PHP applications follow these steps to read from or write to a file:

Opening Files

The fopen() function can be used to open any file in the server's file system. It can also be used to open files via HTTP or FTP on the Internet. Here we will only look at how this function can be used to open files in the server's file system:

    int fopen(string filename, string mode [, string use_include_path])

The argument filename can be the name of the file, or its absolute path. If filename is the name of the file, then it is assumed that the file is in the current working directory.

The second argument indicates whether the file is to be opened for reading, writing, or appending. It can have one of the following possible values:

Value

Description

R

Open the file for reading only.

r+

Open the file for reading and writing.

W

Open the file for writing only and truncate the file to zero length. All the contents of the file will be lost. If the file does not exist, PHP will try to create it.

w+

Open the file for reading and writing. Truncate the file to zero length. If the file does not exist, PHP will try to create it.

A

Open a file for appending data. Data will be written at the end of an existing file. If the file does not exist, then PHP will try to create it.

a+

Open a file for appending and reading data. Data will be written at the end of an existing file. If the file does not exist, then PHP will try to create it.

B

This flag must be used to read/write binary files on operating systems such as Windows that handle such files differently.

The third argument specifies whether PHP should search for files in the include_path too. The include_path can be set in the php.ini configuration file.

The fopen() function returns a file handle if successful, or false on failure. The file handle is used by the operating system to maintain the context of the opened file. Among other things it stores the current data pointer, which gets incremented after read or write calls. The returned file handle should be referred to in all the subsequent file related functions.

The following code opens the binary file C:\temp\job.jpg for reading:

    if (!($fp=fopen("c:/temp/job.jpg", "rb"))) {
        printf("Could not open file job.jpg");
    }

Closing Files

    int fclose(int fp)

The fclose() function is used to close an opened file. The argument fp is the file pointer of the file to be closed. This function returns true on success or false on failure.

It is important to close an open file when you have finished reading or writing it, to free it for access by other scripts or programs. There are operating system specific limits on the number of files that can remain open at any time.

Displaying Files

    int fpassthru(int fp)

The contents of an opened file can be sent to the browser using the fpassthru() function. This function reads the content of the file from the current position in the open file to the end of the file, and writes it to the standard output. The argument fp is the file pointer of the open file. This function returns true on success, false on failure.

If the opened file is a binary file, then open the file using b flag. Otherwise the browser will not be able to render the file properly. The readfile() method can also be used to send the contents of the file to the browser, but use fpassthru() to send the contents of a binary file. The following code sends the contents of the binary file C:\temp\job.jpg to the browser:

    if (!($fp=fopen("c:/temp/job.jpg", "rb"))) {
        printf("Could not open file job.jpg");
    } else {
        fpassthru($fp);
    }

    int readfile(string filename)

The readfile() method takes the file name as an argument. This method assumes the file is a text file. It returns true on success and false on failure.

Reading from Files

    string fread(int fp, int length)

The fread() function can be used to read a string from the open file. The fread() function returns a string of up to length characters from the file with the pointer fp. If the end of the file is reached before the specified length, then the text up to that point is returned.

As a side effect of this call the current position of the file pointer is changed to the next unread character of the file. This is applicable for all read calls that take file handle fp as an argument.

The following code reads the entire file:

    if (!($fp = fopen("a.txt", "r"))( {
        printf("Could not open file a.txt");
    } else {
        while ($buffer = fread($fp, 100)) {
            // Process the read data
        }
    }

    string fgetc(int fp)

The function fgetc() is used to read a single character from the open file. It returns a one character string at the current position of the file handle and increments the current position by one. It returns false (empty string) on reaching the end of the file:

    string fgets(int fp, int length)

The function fgets() reads and returns a string, starting at the current position of the file handle, of up to "length-1" bytes. The reading ends when length–1 bytes have been read, or a new line or end of file is reached. As a side effect of this call the current position of the file handle points to the next unread character:

    string fgetss(int fp, int length [,string allowable_tags])

The function fgetss() is identical to fgets(), except that any HTML and PHP tags are stripped from the string. The argument allowable_tags can be used to specify the list of comma separated tags, which should not be stripped. Note that the tags are still counted towards the length of the string:

    array file(string filename [,int use_include_path])

The function file() reads the contents of file filename into an array. The function returns an array, where each element of the array corresponds to a line, with the end of line (line feed and carriage return) character still attached, in the file on success.

The file() function should be used to read small files only. It should never be used to read big files, as it may unnecessarily increase the memory footprint of the PHP interpreter.

The following code reads the contents of a.txt and outputs it as an HTML document:

    <html>
      <head></head>
      <body>
        <?php
        if (!($fileArray = file("a.txt"))) {
            printf("could not read a.txt file");
        }
        for ($i=0; $i < count($fileArray); $i++) {
            printf("%s<br>", $fileArray[$i]);
        }
        ?>
      </body>
    </html>

Writing to Files

The functions fputs() and fwrite() can be used for writing to files. These two functions are identical:

    int fputs(int fp, string stringtoWrite [,int length]);
    int fwrite(int fp, string stringtoWrite [,int length]);

The first argument fp is the file handle of the file to be written to. The second argument stringToWrite is the string to be written to the file. The third optional argument is the number of characters from the string to write. If this last parameter is not included then the entire string will be written. The return value is true on success, or false on failure.

Navigating within Files

When reading from a file, the current position indicator within the file moves to the next unread character. PHP provides a set of functions for changing the current position indicator within the file:

    int rewind(int fp)

The rewind() function sets the current position indicator to the beginning of the file. The argument fp is the file pointer of the file. The function returns true on success, or false on failure:

    int fseek(int fp, int offset [, int whence])

The fseek() function can be used to set the current position indicator to any position in the file. The argument fp is the file handle of the file. The third argument whence can be any one of the following:

  • SEEK_SET
    Sets position indicator to offset bytes.

  • SEEK_CUR
    Sets position indicator to current location plus offset.

  • SEEK_END
    Sets position indicator to end-of-file plus offset. Note that a negative value can be specified as offset.

The default value of the whence argument is SEEK_SET. The fseek() function returns true on success, false on failure:

    int ftell(int fp)

This function can be used to find the current position within the file. It returns the position in the file:

    int feof(int fp)

feof() can be used to find whether or not the current position is at the end of the file. The function returns true if the file with pointer fp is at the end of the file or if an error occurs; otherwise it returns false.

The following example uses feof() function to read the contents of the file. There is no need to check the return value for end-of-file condition:

    while (feof($fp)) {
        $buffer = fread($fp, 1024);
    }

Copying, Deleting, and Renaming Files

PHP supports functions for copying, deleting, and renaming files. Though copying and renaming files can be implemented using the read, write, and delete APIs, it is almost always easier to use the specific PHP functions:

    int copy(string source, string destination)

The copy() function copies the file source to destination. It returns true on success, false on failure:

    int rename(string oldname, string newname)

This function changes the name of the file oldname to newname. It returns true on success, false on failure:

    int unlink(string filename)

The unlink() function should be used to delete a file permanently. The function returns true on success, false on failure.

Note 

Every file in UNIX is actually a link to a disk block. As long as there is at least one link to a disk block, that block is considered to be in use. When a block is no longer referenced by any link, the OS considers it "free" and will overwrite it with data belonging to another file. So a user can make a backup of a file by just creating another link to it. Then the data is still available even if the first file (link) is deleted, because the second link continues to point to the disk block containing the data, and the OS will not free it as long as it does.

Determining File Attributes

PHP provides a number of functions which can be used to find additional information about the file:

    int file_exists(string filename)

The file_exists() function can be used to check that the file exists. It returns true if the file exists; otherwise false is returned:

    int fileatime(string filename)

The fileatime() function returns the time when the file was last accessed:

    int filectime(string filename)

The filectime() returns the time when the file, either the content or meta data information like permissions, was last modified:

    int filemtime(string filename)

The filemtime() function returns the time when the file content was last modified:

    int filesize(string filename)

The filesize() function returns the size of the file in bytes:

    string filetype(string filename)

The filetype() function returns the type of the file. On success, the return value of filetype() may be one of the following string values:

Value

Description

fifo

Entry is a FIFO (named pipe)

char

Entry is a character special device

dir

Entry is a directory

block

Entry is a block special device

link

Entry is a symbolic link

file

Entry is a regular file

unknown

File type cannot be determined

    void clearstatcache(void)

Most file system calls, which return the details of the file, are very expensive. To avoid this performance overhead, PHP caches the details of the file. This cache can be cleared by calling the clearstatcache() function.

There is a set of functions which indicate the type of the file. These are:

    boolean is_dir(string filename)
    boolean is_executable(string filename)
    boolean is_file(string filename)
    boolean is_link(string filename)

These functions return true if the named file is a directory, an executable file, a regular file, or a symbolic link, respectively:

    boolean is_readable(string filename)
    boolean is_writable(string filename)

The functions is_readable() and is_writable() can be used to find if the PHP script has permissions to read from or write to the named file.

We use some of these functions in the Online Storage Application, later in the chapter.


Table of Contents
Previous Next