This is an archived tutorial from the kirupa.com legacy collection. It covers software that may no longer be available, but it is kept online because the ideas still hold up.
When writing applications for the web,
it's often important to be able to save data. This is
usually done one of two ways: writing data to a file, or
saving it in a database (such as MySQL). Of course, the
easier method (which doesn't require other technologies) is
to write to files, and then read and parse them yourself.
This simpler which is what I discuss here.
So, let's get started:
- To open a file for reading and writing, we start by
using the fopen function. This simply opens up a file
resource for us to use in later functions.
It's worth noting that I opened the file for reading.
Notice the 'r'? This is the mode argument, and allows
you to use the $file variable for reading, or writing,
depending on which you need.
You can see the different modes for opening a file in
the
documentation for the function (under Table 1).
- To read from a file, the easiest way is to utilize
the fread method. This takes two arguments, the file
resource from the previous function (fopen), and a
length argument.
I had to use filesize in order to read to the end of the
file. Otherwise, the function won't know when to stop
reading.
- Writing to a file is done with similar ease. This
time, we'll just use fwrite, which has two required
arguments: the file handle resource, and the string to
write (the third optional argument is the length of the
content to write).
I had to redefine the $handle variable, because the
previous resource was only open for reading.
The Shortcuts
Well, since you know how to open, read, and write files the
full, long way, here are some shortcuts. I tend to avoid
these, but there's really nothing wrong with using them.
Please be aware, both of these require PHP5.
- Rather than fopen and fread, you can simply use
file_get_contents. The only required argument is the
filename, and it'll return a string of the contents.
- Now, the shortcut for fwrite is just as simple…
In the next section, I will cover how to list files in
directories and more!
In the previous section, you got an introduction to using PHP
to manipulate files. In this page, we will pick up from where we
left off and discuss how to list files from a directory.
Listing Files
Occasionally, it's nice to use PHP to list all files in a
certain directory. This can be achieved via the
dir class.
- First, we have to initiate the dir object with
the directory we want to look through. If it's the
current directory, use '.', as this references the
current directory.
- The next part is a little bit more complicated, but
that is because the PHP documentation recommends a
complex but short way to do what we intended.
I use the while control structure, to loop through all
the entries. For the condition, I test if the
$dir->read() returns false (the !== operator tests for
the correct type, so '' would not evaluate to 0 or
false, as it would with a non-type-sensitive operator).
I also define $file inside the expression, but the
assignment will return the final value of $file after
the assignment. The $dir->read() method will return
false in the case that there are no more files, and
it'll break out of the loop.
If you are using html, you will want to use a <br />
instead of a newline character, so that the files will
appear on new lines in your page.
- If you executed the previous code, you will notice
two strange files listed in your script's output: . and
... These are references to the current directory (the
'.'), and the parent directory (the '..').
If you want to exclude these from your list, simply
write an if statement that tests whether the $file
variable is either of those values, and if so, ignore
it.
- It's necessary to close instances of the dir class
when you're done with them, in order to clean the
resource handle, and announce to the operating system
that you're done with it.
This wraps up learning how to list files using PHP. In the next section, you will learn how to upload files from a
directory to the server. Before I send you off to the next section though, for another practical use of being able to
retrieve a list of files from a directory, read Kirupa's
tutorial on
Parsing External Data.
More file handling coverage in the next section!
Yay, this is the previous section! In the
previous section you
learned more practical file handling tricks, and we will
wrap things up on this page.
Uploading Files
Allowing users to upload files is a necessity of many
sites, so, how does one do that, exactly? Turns out, there's
some
handy documentation written on that. Having trouble
getting all that? Well, here's some help that's slightly
easier to digest.
- First, you'll need an html page where the form will
lie. This form must define the max file-size for the
upload, and must have the file upload field itself.
The MAX_FILE_SIZE defines the largest possible
file-size, in bytes, of course. The name attribute of
the upload field (designated by the file value for the
type attribute) is the important part, as we will later
use this in our script to know which file to upload
(this is used to support multiple uploads).
- Next, we have to upload the file. But first, it's
important to understand the $_FILE[] array.
In the $_FILE[] array, there's one entry for each upload
field in the form which sent the user to this script.
So, in our case, there is one index named 'userfield',
for the one field with that name in our form. Each value
in the array is also an associative array, with the
following keys and values (reworded for clarity from
documentation):
Key |
Value |
|
'name'
|
The
filename used on the client's computer.
|
|
'type'
|
The
mime-type of the file (e.g. image/gif). The
browser doesn't always provide this, and the
value should not be assumed to be correct.
|
|
'size' |
Size of
uploaded file (in bytes). |
|
'tmp_name'
|
The
filename given to the uploaded file, which
should immediately be moved and renamed upon
successful upload. The location is irrelevant,
because the methods you use to move the file
(move_uploaded_file, which I use later) are
aware of the location. |
|
'error' |
The error
code (or success code, if 0) for the problem
which occurred during upload. (Error
Codes)
|
Table 1: A summary of the keys
and values
- So, now we can get down to business. We
start by getting the filename we will want to give the
uploaded file, and the directory where we will want to
put it.
The use of basename is absolutely necessary. Without
this, you're running a huge security risk. If a user
were to upload a file with a name that started with a
relative path going up, such as ../../../, they would
eventually get to root, and could navigate to anywhere
on the filesystem by putting in more directories after
the original starting path.
Warning:
It is very
important that you make sure the server has permissions
to write to this directory. If your server is running
any distro of Linux or Mac OS X, you'll likely need to
chmod the directory.
- Next, you simply need to move the uploaded file to $target_file.
I suggest doing this in an if, in order to test for
success.
That's really all there is to it. Pretty simple, huh? You
can expand on this, by reading PHP's documentation on
serializing and
unserializing objects. If you have any questions,
feel free to post them on the
forums.
Just a final word before we wrap up. What you've seen here is freshly baked content without added preservatives, artificial intelligence, ads, and algorithm-driven doodads. A huge thank you to all of you who buy kirupa's books, became a paid subscriber, watch the videos, and/or interact on the forums.
Your support keeps this site going! 😇