Saving a File to the File System

Saving a File to the File System

Your PHP programs can access the server's file system to store and retrieve information. Your programs can create new files, add data to files, and read information from the files. You'll start by writing a program that creates a file and adds data to it.

Introducing the saveSonnet.php Program

The saveSonnet.php program shown in the following code listing opens a file on the server and writes one of Shakespeare's sonnets to that file on the server.


Normally I show you a screen shot of every program, but since this particular program doesn't actually display anything on the screen, that won't be useful to you. The next couple of programs will read this file and display it on the screen, and I'll show you what they look like when the time comes.


$sonnet76 = <<<HERE
Sonnet # 76, William Shakespeare

Why is my verse so barren of new pride,
So far from variation or quick change?
Why with the time do I not glance aside
To new-found methods, and to compounds strange?
Why write I still all one, ever the same,
And keep invention in a noted weed,
That every word doth almost tell my name,
Showing their birth, and where they did proceed?
O! know sweet love I always write of you,
And you and love are still my argument;
So all my best is dressing old words new,
Spending again what is already spent:
For as the sun is daily new and old,
So is my love still telling what is told.


$fp = fopen("sonnet76.txt", "w");
fputs($fp, $sonnet76);


Most of the code stores the content's of Shakespeare's 76th sonnet to a variable called $sonnet76. The remaining three lines save the data in the variable to a text file.

Opening a File with fopen()

The fopen() command is used to open a file. Note that you can only create files on the Web server. You cannot directly create a file on the client machine, because you do not have access to that machine's file system. (If you did, any server-side program would be able to create viruses with extreme ease.) However, as a server-side programmer, you already have the ability to create files on the server. The programs you are writing are themselves files. Your programs can write files as if they are you.


Actually the ownership of files created by your PHP programs can be a little more complicated, depending on your operating system, server, and PHP configurations. Generally, any file created by your program will be owned by a special user called PHP or by the account you were in when you wrote the program. This makes a big difference in an OS like UNIX where file ownership is a major part of the security mechanism. The best way to discover how this works is to write a program that creates a file and then look at that file's properties.

The first parameter of the fopen() function is the filename. This filename can include directory information, or it can be a relative reference.


You should always test your programs, especially if they use a relative reference for a filename. It's possible that your current directory is not the default directory. Also, the filename is based on the actual file system of the server, rather than the URL of the file.

You can create a file anywhere on the server that you have access to. Your files can be in the parts of your directory system open to the Web server (usually subdirectories of public_html or htdocs). Sometimes, though, you might not want your files to be directly accessible to users by typing a URL. You can control access to these files by placing them outside the public html space and by setting the permissions so they can be read by you (and programs you create) but not by anyone else.

Creating a File Handle

When you create a file with the fopen() command, the function returns an integer called a file handle (sometimes also called a file pointer). This special number will be used to refer to the file in subsequent commands. You won't usually be concerned about the actual value of this handle, but you will need to store it in a variable (I usually use $fp) so that your other file access commands know which file to work with.

Examining File Access Modifiers

The final parameter in the fopen() command is an access modifier. PHP supports a number of access modifiers that determine how your program will interact with the file. Files are usually opened for reading, writing, or appending. You can also use a file for simultaneous input and output, but such files are often not needed in PHP, because the relational database techniques you'll learn in the next couple of chapters provide the same capability with more flexibility and a lot less work. However, the other forms of file access (read, write, and output) are extremely useful, because they provide easy access to the file information. (See Table 6.1 for a list of file access modifiers with descriptions.)







program can read from the file



writes to the file, overwriting it if it already exists



writes to the end of the file

"r+" "w+"

read and write


The file access modifiers determine what you can do with the file. Read mode opens a file for input, so your program can read information in from the file. You cannot write data to a file that is opened in read mode. You'll see an example of the read mode in action in the next section, "Loading a File from the Drive System." Write mode allows you to open a file for output access. If the file does not exist, PHP automatically creates it for you.


Be very careful about opening a file in write mode. If a file already exists and you open it for write access, PHP will create a new file, overwriting the old file and destroying its contents.

Append mode allows you to write to a file without destroying the current contents. When you write to a file in append mode, all new data is added to the end of the file.

Start example

The "r+" and "w+" modifiers are used for another form of file access, called "random access," which allows simultaneous reading and writing to the same file. While this is a very useful tool, I won't spend a lot of time on it in this introductory book. The sequential access methods you'll learn in this chapter are fine for simple file storage problems, and the relational database functions that you'll learn in the remainder of this book aren't any more difficult than the random access model, and provide far more power.

End example

Writing to a File

The saveSonnet program opens up the sonnet76.txt file for write access. If there was already a file in the current directory, it is destroyed. The file pointer for the text file is stored in the $fp variable. Once this is done, I can use the fputs() function to actually write data to the file.


You might be noticing a trend here. Most of the file access functions begin with the letter f (fopen(), fclose(), fputs(), fgets(), feof().) This is a convention inherited from the C language. It can sometimes help you remember that a particular function works with files. Of course, every statement in PHP that begins with f isn't necessarily a file function (foreach is a good example), but most of the function names in PHP that begin with f are file-handling commands.

The fputs() function requires two parameters. The first is a file pointer. This tells PHP where to write the data. The second parameter is the text to write out to the file.

Closing a File

The fclose() function tells the system that your program is done working with the file, and should close it up.


Drive systems are much slower than computer memory, and they take a long time to spool up to speed. For that reason, when a program encounters an fputs() command, it doesn't always immediately save the data to a file on the disk. Instead, it adds the data to a special buffer and only writes the data when a sufficient amount is on the buffer or the program encounters an fclose() command. This is why it's important to close your files. If the program ends without encountering an fclose() statement, PHP is supposed to automatically close the file for you, but what's supposed to happen and what actually happens are often two very different things.