Friday, September 12, 2008

PHP - Filing

Manipulating files is a basic necessity for serious programmers and PHP gives you a great deal of tools for creating, uploading, and editing files.

This section of the PHP tutorial is completely dedicated to how PHP can interact with files. After completing this section you should have a solid understanding of all types of file manipulation in PHP!

PHP - Files: Be Careful

When you are manipulating files you must be very careful because you can do a lot of damage if you do something wrong. Common errors include editing the wrong file, filling a hard-drive with garbage data, and accidentally deleting a file's contents.

It is our hope that you will be able to avoid these and other slipups after reading this tutorial. However, we know that there are so many places where code can take a wrong turn, so we urge you to take extra care when dealing with files in PHP.

PHP - Files: Overview

The presentation of the file lessons will begin with how to create, open, and close a file. After establishing those basics, we will then cover other important file tasks, such as: read, write, append, truncate, and uploading files with PHP.

PHP - File Create##########

Before you can do anything with a file it has to exist! In this lesson you will learn how to create a file using PHP.

PHP - Creating Confusion
In PHP, a file is created using a command that is also used to open files. It may seem a little confusing, but we'll try to clarify this conundrum.

In PHP the fopen function is used to open files. However, it can also create a file if it does not find the file specified in the function call. So if you use fopen on a file that does not exist, it will create it, given that you open the file for writing or appending (more on this later).
PHP - How to Create a File

The fopen function needs two important pieces of information to operate correctly. First, we must supply it with the name of the file that we want it to open. Secondly, we must tell the function what we plan on doing with that file (i.e. read from the file, write information, etc).

Since we want to create a file, we must supply a file name and tell PHP that we want to write to the file. Note: We have to tell PHP we are writing to the file, otherwise it will not create a new file.

PHP Code:

$ourFileName = "testFile.txt";
$ourFileHandle = fopen($ourFileName, 'w') or die("can't open file");
fclose($ourFileHandle);

The file "testFile.txt" should be created in the same directory where this PHP code resides. PHP will see that "testFile.txt" does not exist and will create it after running this code. There's a lot of information in those three lines of code, let's make sure you understand it.

1. $ourFileName = "testFile.txt";

Here we create the name of our file, "testFile.txt" and store it into a PHP String variable $ourFileName.
2. $ourFileHandle = fopen($ourFileName, 'w') or die("can't open file");

This bit of code actually has two parts. First we use the function fopen and give it two arguments: our file name and we inform

PHP that we want to write by passing the character "w".
Second, the fopen function returns what is called a file handle, which will allow us to manipulate the file. We save the file handle into the $ourFileHandle variable. We will talk more about file handles later on.

3. fclose($ourFileHandle);

We close the file that was opened. fclose takes the file handle that is to be closed. We will talk more about this more in the file closing lesson.

PHP - Permissions

If you are trying to get this program to run and you are having errors, you might want to check that you have granted your PHP file access to write information to the hard drive. Setting permissions is most often done with the use of an FTP program to execute a command called CHMOD. Use CHMOD to allow the PHP file to write to disk, thus allowing it to create a file.

In the near future Tizag.com will have a more in-depth tutorial on how to use CHMOD to set file permissions.

PHP - File Open###########
In the previous lesson we used the function fopen to create a new file. In this lesson we will be going into the details of this important

function and see what it has to offer.

PHP - Different Ways to Open a File
For many different technical reasons, PHP requires you to specify your intentions when you open a file. Below are the three basic ways to open a file and the corresponding character that PHP uses.

* Read: 'r'

Open a file for read only use. The file pointer begins at the front of the file.

* Write: 'w'

Open a file for write only use. In addition, the data in the file is erased and you will begin writing data at the beginning of the file. This is also called truncating a file, which we will talk about more in a later lesson. The file pointer begins at the start of the file.

* Append: 'a'

Open a file for write only use. However, the data in the file is preserved and you begin will writing data at the end of the file. The file pointer begins at the end of the file.

A file pointer is PHP's way of remembering its location in a file. When you open a file for reading, the file pointer begins at the start of the file. This makes sense because you will usually be reading data from the front of the file.

However, when you open a file for appending, the file pointer is at the end of the file, as you most likely will be appending data at the end of the file. When you use reading or writing functions they begin at the location specified by the file pointer.

PHP - Explanation of Different Types of fopen


These three basic ways to open a file have distinct purposes. If you want to get information out of a file, like search an e-book for the occurrences of "cheese", then you would open the file for read only.

If you wanted to write a new file, or overwrite an existing file, then you would want to open the file with the "w" option. This would wipe clean all existing data within the file.

If you wanted to add the latest order to your "orders.txt" file, then you would want to open it to append the data on to the end. This would be the "a" option.

PHP - File Open: Advanced


There are additional ways to open a file. Above we stated the standard ways to open a file. However, you can open a file in such a way that reading and writing is allowable! This combination is done by placing a plus sign "+" after the file mode character.

* Read/Write: 'r+'

Opens a file so that it can be read from and written to. The file pointer is at the beginning of the file.

* Write/Read: 'w+'

This is exactly the same as r+, except that it deletes all information in the file when the file is opened.

* Append: 'a+'

This is exactly the same as r+, except that the file pointer is at the end of the file.
PHP - File Open: Cookie Cutter Below is the correct form for opening a file with PHP. Replace the (X) with one of the options above (i.e. r, w, a, etc).

Pseudo PHP Code:


$ourFileName = "testFile.txt";
$fh = fopen($ourFileName, 'X') or die("Can't open file");
fclose($fh);

PHP - File Open: Summary
You can open a file in many different ways. You can delete everything and begin writing on a clean slate, you can add to existing data, and you can simply read information from a file. In later lessons we will go into greater detail on how each of these different ways to open a file is used in the real world and give some helpful examples.

PHP - File Close####################
The next logical step after you have opened a file and finished your business with it is to close that file down. You don't want an open file running around on your server taking up resources and causing mischief!

PHP - File Close Description

In PHP it is not system critical to close all your files after using them because the server will close all files after the PHP code finishes execution. However the programmer is still free to make mistakes (i.e. editing a file that you accidentally forgot to close). You should close all files after you have finished with them because it's a good programming practice and because we told you to!

PHP - File Close Function

In a previous tutorial, we had a call to the function fclose to close down a file after we were done with it. Here we will repeat that example and discuss the importance of closing a file.

PHP Code:


$ourFileName = "testFile.txt";
$ourFileHandle = fopen($ourFileName, 'w') or die("can't open file");
fclose($ourFileHandle);

The function fclose requires the file handle that we want to close down. In our example we set our variable "$fileHandle" equal to the file handle returned by the fopen function.

After a file has been closed down with fclose it is impossible to read, write or append to that file unless it is once more opened up with the fopen function. Write, then this function might not work the way you expect it to.

PHP - File Delete##########
You know how to create a file. You know how to open a file in an assortment of different ways. You even know how to read and write data from a file!

Now it's time to learn how to destroy (delete) files. In PHP you delete files by calling the unlink function.

PHP - File Unlink
When you view the contents of a directory you can see all the files that exist in that directory because the operating system or application that you are using displays a list of filenames. You can think of these filenames as links that join the files to the directory you are currently viewing.

If you unlink a file, you are effectively causing the system to forget about it or delete it!

Before you can delete (unlink) a file, you must first be sure that it is not open in your program. Use the fclose function to close down an open file.

PHP - Unlink Function

Remember from the PHP File Create lesson that we created a file named testFile.txt.

PHP Code:


$myFile = "testFile.txt";
$fh = fopen($myFile, 'w') or die("can't open file");
fclose($fh);

Now to delete testFile.txt we simply run a PHP script that is located in the same directory. Unlink just needs to know the name of the file to start working its destructive magic.

PHP Code:


$myFile = "testFile.txt";
unlink($myFile);

The testFile.txt should now be removed.PHP - Unlink: Safety First!

With great power comes a slough of potential things you can mess up! When you are performing the unlink function be sure that you are deleting the right file!

PHP - File Append###########
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.

PHP - File Open: Append
If we want to add on to a file we need to open it up in append mode. The code below does just that.

PHP Code:

$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.

PHP - File Write: Appending Data

Using the testFile.txt file we created in the File Write lesson , we are going to append on some more data.

PHP Code:


$myFile = "testFile.txt";
$fh = fopen($myFile, 'a') or die("can't open file");
$stringData = "New Stuff 1\n";
fwrite($fh, $stringData);
$stringData = "New Stuff 2\n";
fwrite($fh, $stringData);
fclose($fh);

You should noticed that the way we write data to the file is exactly the same as in the Write lesson. The only thing that is different is that the file pointer is placed at the end of the file in append mode, so all data is added to the end of the file.

The contents of the file testFile.txt would now look like this:

Contents of the testFile.txt File:

Floppy Jalopy
Pointy Pinto
New Stuff 1
New Stuff 2

PHP - Append: Why Use It?

The above example may not seem very useful, but appending data onto a file is actually used everyday. Almost all web servers have a log of some sort. These various logs keep track of all kinds of information, such as: errors, visitors, and even files that are installed on the machine.

A log is basically used to document events that occur over a period of time, rather than all at once. Logs: a perfect use for append!

PHP - File Truncate###########
As we have mentioned before, when you open a file for writing with the paramater 'w' it completely wipes all data from that file. This action is also referred to as "truncating" a file. Truncate literally means to shorten.

PHP - File Open: Truncate
To erase all the data from our testFile.txt file we need to open the file for normal writing. All existing data within testFile.txt will be lost.

PHP Code:

$myFile = "testFile.txt";
$fh = fopen($myFile, 'w');
fclose($fh);

PHP - Truncate: Why Use It?
Truncating is most often used on files that contain data that will only be used for a short time, before needing to be replaced. These type of files are most often referred to as temporary files.

For example, you could create an online word processor that automatically saves every thirty seconds. Every time it saves it would take all the data that existed within some HTML form text box and save it to the server. This file, say tempSave.txt, would be truncated and overwritten with new, up-to-date data every thirty seconds.

This might not be the most efficient program, but it is a nice usage of truncate.

No comments: