Image

PHP - PHP File Handling - PHP File Handling

PHP file handling

File handling is a very important part of any web application. Many times you need to open a file and process the file according to the specific requirement. Php provide you function to do these functions on file simply. You may open file in mode which is most applicable.

First we need to know about the available file format so that we are comfortable while coding

  1. r -> Open the file in read only mode. With this mode you are only allowed to read and no editing is allowed
  2. w -> Open the file in write mode. You are allowed to write in the file
  3. r+ - > It will open file in read/write mode. The pointer is placed at file beginning and data is not truncatedw+ - > It will open file in read/write mode. The file content is truncated to length 0 and pointer is placed to beginning of file. It will create a new file if one does not exist.
  4. a -> It appends data to end of file contents.If file does not exist then one is created.
  5. a+ -> It open the file in read/append mode. It also write data at end of file contents
  6. x -> Creates a new file in write mode. Throws error if file already exist.
  7. x+ -> Open file Read/Write mode. It also create file and throw error in case file already exist

Append file

So far we have learned how to open, close, read, and write to a file. However, the ways in which we have written to a file so far have caused the data that was stored in the file to be deleted. If you want to append to a file, that is, add on to the existing data, then you need to open the file in append mode.

If we want to add on to a file we need to open it up in append mode. The code below does just that.

$myFile = "testFile.txt";
$fh = fopen($myFile, 'a');
If we were to write to the file it would begin writing data at the end of the file.
Reading Files
Problem :
You want to read the contents of a local or remote file into a string or an array.
Solution
Use PHP’s file_get_contents() or file() function:
<?php
// set the file name
$file = "dummy.txt";
C h a p t e r 6 :Wo r k i n g w i t h F i l e s a n d D i r e c t o r i e s 189
// read file contents into an array
$dataArr = file($file);
print_r($dataArr);
// read file contents into a string
$dataStr = file_get_contents($file);
echo $dataStr;
?>

Comments

The file_get_contents() function is a fast and efficient way to read an entire file into a single string variable, whereupon it can be further processed. The file() function is similar, except that it reads a file into an array, with each line of the file corresponding to an element of the array.

If you’re using an older PHP build that lacks the file_get_contents() function, you can instead use the fread() function to read a file into a string.

Here’s how:
<?php
// define file to read
$file = "dummy.txt";
// open file
$fp = fopen($file, "rb") or die ("Cannot open file");
// read file contents into string
$dataStr = fread($fp, filesize($file));
echo $dataStr;
// close file
fclose($fp) or die("Cannot close file");
?

If you’re trying to read a file over a network link, it may not always be a good idea to slurp up a file in a single chunk due to network bandwidth considerations.


Writing Files
Problem
You want to write a string to a file.

Solution

Use the file_put_contents() function:
<?php
// define string to write
$data = "All the world's a stage\r\nAnd all the men and ↵
women merely players";
// write string to file
file_put_contents('shakespeare.txt', $data) or die("Cannot write to ↵
file"); echo "File successfully written.";
?>

Comments

The file_put_contents() function provides an easy way to write data to a file.

The file will be created if it does not already exist, and overwritten if it does. The return value of the function is the number of bytes written.

If you’re using an older PHP build that lacks the file_put_contents() function, you can use the fwrite() function to write to a file instead. Here’s how:

<?php
// define string to write
$data = "All the world's a stage\r\nAnd all the men and ↵
women merely players";
// open file
$fp = fopen('shakespeare.txt', "wb+") or die ("Cannot open file");
C h a p t e r 6 :Wo r k i n g w i t h F i l e s a n d D i r e c t o r i e s 197
// lock file
// write string to file
if (flock($fp, LOCK_EX)) {
fwrite($fp, $data) or die("Cannot write to file");
flock($fp, LOCK_UN);
echo "File successfully written.";
} else {
die ("Cannot lock file");
}
// close file
fclose($fp) or die ("Cannot close file");
?>

Here, the fwrite() function is used to write a string to an open file pointer, after the file has been opened for writing with fopen() and the w+ parameter.

Notice the call to flock() before any data is written to the file—this locks the file, stops other processes from writing to the file, and thereby reduces the possibility of data corruption. Once the data has been successfully written, the file is unlocked. Locking is discussed in greater detail in the listing in “6.8: Locking and Unlocking Files.


Deleting Files

Problem

You want to delete a file.

Solution

Use PHP’s unlink() function:
<?php
// set file name
$file = "shakespeare.asc";
// check if file exists
// if it does, delete it
if (file_exists($file)) {
unlink ($file) or die("Cannot delete file '$file'");
echo "File successfully deleted.";
} else {
die ("Cannot find file '$file'");
}
?>

Comments

To delete a file with PHP, simply call the unlink() function with the file name and path. The function returns true if the file was successfully deleted.