PHP File Handling

PHP can be used to handle files on the server. You can create, access (or read) and manipulate files dynamically using the PHP file system functions. Since PHP is a server side programming language, it allows you to work with files and directories stored on the web server.

images/articles/php/php-file-handling.jpg

Path Information

The pathinfo() function creates an associative array containing three components of a path - the directory name, the base name, and the extension.

For example: /home/www/htdocs/book/chapter10/index.html

The pathinfo() function can be used to parse this path into the following four components:

  1. Directory name: /home/www/htdocs/book/chapter10
  2. Base name: index.html
  3. File extension: html
  4. File name: index

Managing Files

The information you save on your hard drive is organized into files. Rather than storing files in one big file drawer, making them difficult to find, files are stored in many drawers, called directories or folders. The system of files and directories is called a file system.

A file system is organized in a hierarchical structure, with a top level that is a single directory called root, such as c:\ on Windows or / on Linux or Mac. The root directory contains other directories, and each directory can contain other directories, and so on. The file system’s structure can go down many levels.

A directory is a type of file that you use to organize other files. It contains a list of files and the information needed for the operating system to find those files. A directory can contain both files and other directories.

Files can be checked (to see if they exist, for example), copied, deleted, and renamed, among other things.

Getting Information about Files

Often you want to know information about a file. PHP has functions that allow you to find out file information from within a script. You can find out whether a file exists with the file_exists statement, as follows:

$result = file_exists('stuff.txt');

After this statement, $result contains either true or false. The function is often used in a conditional statement, such as the following:

if (!file_exists('stuff.txt'))
{
echo 'File not found!';
}

When you know the file exists, you can find out information about it.

is_file('stuff.txt')

Tests whether the file is a regular file, rather than a directory or other special type of file

is_dir('stuff.txt')

Tests whether the file is a directory

is_executable('do.txt')

Tests whether the file is executable

is_writable('stuff.txt')

Tests whether you can write to the file

is_readable('stuff.txt')

Tests whether you can read the file

fileatime('stuff.txt')

Returns the time when the file was last accessed

filectime('stuff.txt')

Returns the time when the file was created

filemtime('stuff.txt')

Returns the time when the file was last modified

filegroup('stuff.txt')

Returns the group ID of the file

fileowner('stuff.txt')

Returns the user ID of the owner of the file

filesize('stuff.txt')

Returns the file size in bytes

filetype('stuff.txt')

Returns the file type File type (such as file, dir, link, char), or false if error or can’t identify type

basename('/t1/do.txt')

Returns the filename from the path do.txt

dirname('/t1/do.txt')

Returns the directory name from the path /t1

Reading and Writing Files

Newline Characters: The newline character, represented by the \n character sequence (\r\n on Windows), denotes the end of a line within a file. Keep this in mind when you need to input or output information one line at a time.

In most applications, you store the data needed by the application in a MySQL database. However, occasionally you need to read or write information in a text file that isn’t a database. You use PHP statements to read from or write to a flat file. Using a flat file requires three steps:

  1. Open the file.
  2. Write data into the file or retrieve data from the file.
  3. Close the file.

1. Create a File

You need to create what's known as a handle before you can do anything with a file's contents. Likewise, once you have finished working with that resource, you should destroy the handle.

$my_file = 'file.txt';
$handle = fopen($my_file, 'w') or die('Cannot open file: '. $my_file);

2. Open a File

The first step, before you can write information into or read information from a file, is to open the file. The PHP fopen() function is used to open a file. It requires two arguments - first the file name and then mode in which to operate. The following is the general format for the statement that opens a file:

$fh = fopen('filename', 'mode');

The variable, $fh, referred to as a file handle, is used in the statements that write data to or read data from the open file so that PHP knows which file to write into or read from. The $fh variable contains the information that identifies the location of the open file.

$my_file = 'file.txt';
$handle = fopen($my_file, 'w') or die('Cannot open file: '. $my_file);

If an attempt to open a file fails, then the fopen() returns false otherwise it returns a file pointer which is used for further reading or writing to that file. After making a changes to the opened file it is important to close it with the fclose() function.

3. Read from a File

Once a file is opened using fopen function, it can be read with a function called fread(). This function requires two arguments - the file pointer and the length of the file expressed in bytes. The length of the file can be found using the filesize() function which takes the file name as its argument and returns the size of the file expressed in bytes.

$my_file = 'file.txt';
$handle = fopen($my_file, 'r');
$data = fread($handle, filesize($my_file));

You can read from a file by using the fgets() statement, which has the following general format:

$line = fgets($fh);

In this statement, $fh holds the pointer to the open file. This statement reads a string until it encounters the end of the line or the end of the file, whichever comes first, and stores the string in $line. To read an entire file, you keep reading lines until you get to the end of the file.

PHP recognizes the end of the file and provides a function feof() to tell you when you reach the end of the file. The following statements read and display all the lines in the file:

while (!feof($fh))
{
 $line = fgets($fh);
echo $line;
}

Reading Specific Number of Characters

Sometimes you want to read strings of a certain size from a file. You can tell fgets() to read a certain number of characters by using the following format:

$line = fgets($fh, n);

This statement tells PHP to read a string that is n-1 characters long until it reaches the end of the line or the end of the file.

Reading a File into an Array

It is often handy to have the entire file in an array. You can do that with the following statements:

$fh = fopen('file2.txt', 'r');
while (!feof($fh))
{
 $content[] = fgets($fh);
}
fclose($fh);

Reading a File into a String

Sometimes putting the entire contents of a file into one long string can be useful. For example, you might want to send the file contents in an e-mail message. PHP provides a function for reading a file into a string, as follows:

$content = file_get_contents('file2.txt', 1);

Reading a CSV File into an Array

The fgetcsv() function parses each line of a file marked up in CSV format.

4. Write to a File

After you open the file, you can write into it by using the fwrite statement. A new file can be written or text can be appended to an existing file using the PHP fwrite() function. This function requires two arguments - a file pointer and the string of data that is to be written.

$my_file = 'file.txt';
$handle = fopen($my_file, 'w') or die('Cannot open file: '. $my_file);
$data = 'This is the data';
fwrite($handle, $data);

5. Append to a File

$my_file = 'file.txt';
$handle = fopen($my_file, 'a') or die('Cannot open file: '. $my_file);
$data = 'New data line 1';
fwrite($handle, $data);
$new_data = "\n" . 'New data line 2';
fwrite($handle, $new_data);

6. Close a File

To close a file after you have finished reading or writing it, use the following statement:

fclose($fh);

In this statement, $fh is the file handle variable you created when you opened the file.

$my_file = 'file.txt';
$handle = fopen($my_file, 'w') or die('Cannot open file: '. $my_file);
//write some data here
fclose($handle);

7. Delete a File

You can delete files or directories using the unlink() function.

$my_file = 'file.txt';
unlink($my_file);

After this statement, the file is deleted.

If the file doesn’t exist, unlink doesn’t complain. It acts the same as if it had deleted the file.

8. Copy File

You can copy an existing file into a new file. After copying, you have two copies of the file with two different names. Copying a file is often useful for backing up important files. To copy a file, use the copy statement, as follows:

copy('fileold.txt', 'filenew.txt');
copy('fileold.txt', 'newdir/filenew.txt');

This statement copies fileold.txt, an existing file, into filenew.txt. If a file with the name filenew.txt already exists, it’s overwritten. If you don’t want to overwrite an existing file, you can prevent it by using the following statements:

if (!file_exists('filenew.txt'))
{
copy('fileold.txt', 'filenew.txt');
}
 else
{
echo 'File already exists!';
}

9. Rename File

You can rename a file by using the rename statement, as follows:

rename('old_name.txt', 'new_name.txt');

If you attempt to rename a file with the name of a file that already exists, a warning is displayed and the file is not renamed.

Modes of Files and Purpose

  1. r: Opens the file for reading only; Places the file pointer at the beginning of the file.
  2. r+: Opens the file for reading and writing; Places the file pointer at the beginning of the file.
  3. w: Opens the file for writing only; Places the file pointer at the beginning of the file and truncates the file to zero length. If files does not exist then it attempts to create a file.
  4. w+: Opens the file for reading and writing only; Places the file pointer at the beginning of the file and truncates the file to zero length. If files does not exist then it attempts to create a file.
  5. a: Opens the file for writing only; Places the file pointer at the end of the file. If files does not exist then it attempts to create a file.
  6. a+: Opens the file for reading and writing only; Places the file pointer at the end of the file. If files does not exist then it attempts to create a file.