Reading files with PHP

Reading files with PHP Posted in PHP | 2 Comments

Today we will start a series of tutorials about file manipulations. The series will include file reading and writing. Then we will see how to copy, move or delete a file. We will also go throught directory creation and listing. Latter we will review change of user/group
rights of both files and folders and renaming. Of course our tutorial will include a lot of examples, that most of the time make reading the text around them needless.

Today’s tutorial is about file reading and writing. It is separated in two parts named suprisingly File Reading and File Writing.

First of all you must make sure that you have permissions. This is a complex subject that includes FileSystem permissions, PHP restrictions and also Apache HTTP server configuration. For the purpose of our tutorial I assume that you have them set. Let’s go then. The starting point of every file operation is getting a file handle that will point to our file. This is done by using fopen() function.

1
2
3
4
5
6
7
<?php
// Open Unix file
$handle = fopen("/home/phpjabbers/somefile.txt", "r");
// Open Windows file. Mind that you have to escape the backslashes or I advise you to use forward slashes.
$handle = fopen("c:\data\info.txt", "rt");
$handle = fopen("c:/data/info.txt", "rt");
?>

There are several ways to open the file, they are called modes, and it all depends on what you want to do with it. If you just want to deal with already existing file and you do not want to delete it’s content you have to use the following two modes:

r – opens the file for reading only and places the cursor at the beginning of the file.
r+ – opens the file for reading and writing and places the cursor at the beginning of the file.

If you want to create a new file or replace the existing one you have to use one of the following two modes:

w – opens the file for writing only and places the cursor at the beginning of the file. If the file exists it empties it’s contents (truncates the file to zero length). It the file does not exist, it makes an attempt to create it.
w+ – the same as above only that this time the file is open for reading also.

Another two writing modes allow us different approach:

a – opens the file for writing only and places the cursor at the end of it. If the file does not exist, attempt to create it.
a+ – opens the file for reading and writing and places the cursor at the end of it. If the file does not exist, attempt to create it.

The last two modes are used when we want to create a file.

x – create a file and open it for writing only. This mode places the file pointer at the beginning of the file. An important notice about this mode is that, if the file already exists, the function will fail and will return FALSE.
x+ – the same as above but create and open the file for reading also.

IMPORTANT: When working with files on Windows based operating systam there are two more modes that you must know. They are combined with the other file open parameters.

t – is used when you are working with text files. What is does is translate your line ending characters (n to rn).
b – this mode must be used when working with non-text files. It is strongly recommended that you use b flag when opening files on Windows. If you don’t you might experience strange problems with your file.

Now that we have our file we can start working with it.

PART 1 – FILE READING ( examples included )

First we will focus on reading files. There are several way to do it. We will start with reading text files. Most of the time we need to read our file line by line. For this operation we use this function – file(); It reads the entire file into array.

file() – Reads text file into an array.

1
2
3
4
5
6
7
<?php
// file example
$lines = file("/tmp/files/InputTextFile.txt");
foreach ($lines as $line_num => $line) {
    echo "Line #{$line_num} : " . $line . "n";
}
?>

As you can see it is very simple to output text file content. What more can we add here. Just that file() supports a few optional parameters:

FILE_USE_INCLUDE_PATH – Search for the file in the include_path.
FILE_IGNORE_NEW_LINES – Do not add newline at the end of each array element(in our case $line).
FILE_SKIP_EMPTY_LINES – Skip empty lines.

A similar function that reads the entire content of a file, but this time to a string is file_get_contents(). It supports two additional parameters, which sometimes can be very helpfull: offset and maxlen bytes (they were added in PHP 5.1). Offset specifies where to start
reading from, and maxlen specifies how many bytes to read from the source. This function is bynary safe.

file_get_contents() – Reads entire file into a string. It also shows how to read 1KB starting at the 128th byte.

1
2
3
4
5
<?php
// file_get_contents example
$file = file_get_contents("/tmp/files/InputTextFile.txt",0,null,128,1024);
echo $file;
?>

Here is another example this time reading remote file.

1
2
3
4
5
<?php
// file_get_contents example
$file = file_get_contents("http://www.example.com/tmp/files/InputTextFile.txt");
echo $file;
?>

More direct way to print the file to the buffer is readfile() function. What is does is just that. You do not even have to echo it. It returns the bytes that have been read.

readfile – Outputs the entire file to the output buffer

1
2
3
4
5
6
<?php
// readfile() example
$file = "/tmp/files/InputTextFile.txt";
$bytesRead = readfile($file);
echo $bytesRead;
?>

The next function that can help us reading a file is fgets(). It reads a line starting from the file pointer position and returns it as a string. You can also specify the lenght of bytes you want it to read. If you tend to use it, have in mind, that reading file ends when length – 1 bytes have been read, a newline is reached, or EOF is reached (whichever comes first). This function requires file handle to operate with. In our example we read our file in 8KB chunks at most.

fgets() – Gets a line from file pointer

1
2
3
4
5
6
7
8
9
10
11
12
13
<?php
// fgets example
// Windows OS
$file = "c:/tmp/files/InputTextFile.txt";
$handle = fopen($file, "rt");
if ($handle) {
    while (!feof($handle)) {
        $buffer = fgets($handle, 8192);
        echo $buffer;
    }
    fclose($handle);
}
?>

The last function that we will take a look at and show an example of it is fread(). It is used to read binary files. It takes a file handle and reads length bytes from the file pointer. Reading file ends when length bytes or 8192 bytes (8KB) have been read,
end of file (EOF) is reached or when a packet becomes available (for network streams), whichever comes first.

fread() – Binary-safe file read

1
2
3
4
5
6
7
8
<?php
// fread example
$file = "/tmp/files/picture.gif";
// REMEMBER: If this is Windows OS you have to use "rb"
$handle = fopen($file, "r");
$contents = fread($handle, filesize($file));
fclose($handle);
?>

This example shows how you can read binary files from the web.

1
2
3
4
5
6
7
8
<?php
$handle = fopen("http://www.example.com/picture.gif", "r");
$contents = '';
while (!feof($handle)) {
    $contents = $contents . fread($handle, 8192);
}
fclose($handle);
?>

It is not much of a use to print the contents of a binary file, but it you want to write it to a new file this function is the way to do it.

Advertisements
By Rz Rasel Posted in Php

One comment on “Reading files with PHP

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s