Great Templates

FEATURED WEB TEMPLATES

Amazon Books

Learn PHP

PHP Training
Zend Cert Training Zend Certified Engineer Zend PHP Pro

PHP: File Handling In PHP


Table of Contents:

  • 1. Introduction
  • 2. Mode of Access
  • 3. Create and Write to File
  • 4. Reading the File
  • 5. Copying and Deleting File

1. Introduction to File Handling in PHP - Introduction

Introduction
This tutorial will concentrate on the basic methods used to handle files in PHP. There are multiple functions available in PHP for these types of operation, but we will only be concentrating on some of the more important functions that PHP provides for file handling. This should leave you with enough insight to continue on your own.


This tutorial assumes several things about the reader:

  • You are familiar with PHP
  • You have access to a server or servers running the PHP package
  • You have read/write privileges to the root folder on your server

The easiest way to provide yourself with read/write privileges to a file and/or folder on your server is to open an ftp session to your active directory and use the CHMOD command to grant full permissions to the target file/folder. If this option is not open to you, you can also use the chmod() function in PHP:

bool chmod (string filename, int mode)

This function will return a boolean true or false, where true is success and false is a change of permissions failure. For our example, you will require the permissions of the root folder on your server to be set to 777.

2. Selecting a Mode of Access

Selecting a Mode of Access
Before working with a file, it must exist. Lets use the fopen() function to create and open a file:

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

The fopen() function will attempt to open a stream to the specified file. Using the correct mode parameter is very important at this point, as it identifies the type of file access that will be required. Here is a list of all possible mode parameters you can use with the fopen() function:

mode Description
\\\\'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.


3. Create and Write to File

Create and Write to File
Let\\\\'s use the \\\\'a\\\\' mode to open/create our file. This will append any new data to the end of the file, but opens the file access for writing only. If the file does not exist, this mode will attempt to create it first:

01
02
03
04
05
06
07
08
09
10

$data = "This is a new file entry!\\\\n";
$file = "newfile.txt";
if (!$file_handle = fopen($file,"a")) { echo "Cannot open file"; }
if (!fwrite($file_handle, $data)) { echo "Cannot write to file"; }
echo "You have successfully written data to $file";
fclose($file_handle);
?>


The above code will first assign a reference to your filename and store that reference in memory for later use. From this point forward, refer to your file through the use of your file reference - this is the only way PHP will understand what you are trying to work with. Using the file reference we then open the file for append access. If that action is successful, we write a string of data to your file. Multiple runs of this script will append the data to the end of your file due to the mode we have selected. After you\\\\'re done with your file, don\\\\'t forget to close it!


As you can see, there were 2 new PHP file handling functions introduced in our example, fwrite() and fclose():

int fwrite (resource handle, string string [, int length])
bool fclose (resource handle)

The fwrite() function will return the number of bytes written, or FALSE
on error. The fclose function returns true on success or false on failure.


If your example script runs properly, you should see the message "You have successfully written data to newfile.txt". If you receive the "Cannot open file" error, chances are your permissions are not set properly for the folder you are trying to create your file in. If you receive the error message "Cannot write to file", your file has likely been deleted.

4. Reading the File

Reading the File
We will now enhance the prior example, providing a means to read the contents of a file after writing to it. Reading from a file requires the use of the fread() function:

string fread (resource handle, int length)

The fread() function reads up to length bytes from the file pointer referenced by handle. Reading stops when length bytes have been read, EOF (end of file) is reached, or (for network streams) when a packet becomes available, whichever comes first.

1
2
3
4
5
6
7
8
9

$file = "newfile.txt";
if (!$file_handle = fopen($file,"r")) { echo "Cannot open file."; }
if (!$file_contents = fread($file_handle, filesize($file))) { echo "Cannot retrieve file contents."; }
else { echo "$file_contents"; }
fclose($file_handle);
?>


As you can see in the example, we are opening the file using a different mode of access. We are using the \\\\'r\\\\' mode, which allows you to read from the file. The \\\\'r\\\\' mode will open the file for read only access, placing the file pointer at the beginning of the file. The length parameter is used to tell the fread() function how many bytes to read. To retrieve the length value, in bytes, use the PHP filesize() function.


A successful run of the example script, provided the file exists and has data in it, will output the file contents to the screen.

5. Copying and Deleting Files

Copying and Deleting Files
To copy a file, the copy() function is used:

bool copy(string source_file,string destination_file)

The copy() function will return true if the file was correctly copied, or false if there was an error.

1
2
3
4
5
6
7
8

$log_folder = "logs";
$log_name1 = "logs.txt";
if (!(copy($log_folder,$log_name1))) { echo "Error copying $log_name1 to $log_folder"; }
else { echo "File successfully copied"; }
?>


Assuming that you have a folder named logs, a successful run of this script should copy the file log.txt from your root folder to your logs folder.


The rename() function is very similar in context to the copy() function:

bool rename(string old_file,string new_file)

Considering the name of the functions so far, it may come as a surprise that the function to delete is called unlink():

bool unlink(string filename)

Both the rename() and unlink() functions return true upon successful completion, or false if the operation did not complete successfully. Let\\\\'s try to build a meaningful script using these functions:

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16

$log_folder = "logs";
$log_name1 = "logs.txt";
$log_name2 = "logs.txt.old";
$log_name3 = "logs.txt.archive";
if (!(unlink($log_name3))) { echo "Error deleting $log_name3
"; }
else { echo "$log_name3 deleted successfully
"; }
if (!(rename($log_name2,$log_name3))) { echo "Error renaming $log_name2 to $log_name3
"; }
else { echo "$log_name2 successfully renamed to $log_name3
"; }
if (!(rename($log_name1,$log_name2))) { echo "Error renaming $log_name1 to $log_name2
"; }
else { echo "$log_name1 successfully renamed to $log_name2
"; }
if (!(copy($log_folder,$log_name1))) { echo "Error copying $log_name1 to $log_folder
"; }
else { echo "$log_name1 copied to $log_folder successfully
"; }
?>



As you can see, this is a short script to backup log files - run at whatever interval is suitable. Assuming the filenames listed exist, and the folder \\\\'log\\\\' exists and you have permissions to write to it - the script should first delete your archived log file, then rename your old log files to an archive version, and finally copy your log file to an old version.
 


Learn PHP | Zend Certified Engineer | Zend PHP Pro | PHP Web Apps | Web Hosting Service | Low Cost Domain Names | Great Templates | Great Books | Testimonials | Tech.Articles | TOS | AUS | Home | Linux Apache MySQL PHP