PHP, Filesystems and File I/O

From Techotopia
Revision as of 18:40, 4 June 2007 by Neil (Talk | contribs) (New page: One of the benefits of PHP being a server side scripting environment is that it gives the web developer easy access to the filesystem of the server on which the web server is running. This...)

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

One of the benefits of PHP being a server side scripting environment is that it gives the web developer easy access to the filesystem of the server on which the web server is running. This gives us the ability to create, open, delete, read and write files. We can also traverse the directory hierarchy of the server systems to do things like get directory listings and create new sub-directories.

In this chapter we will cover all aspects of interecting with files and the filesystem in details.

Opening and Creating Files in PHP

Existing files are opened, and new files created using the PHP fopen function. The fopen function accepts two arguments and returns a file handle which is subsequently used fo all future read and write interactions with that file. The first argument is the name (including the path) of the file to open. This path is relative to the web server root, not your server's filesystem root. The second argument is an attribute indicating the mode in whcih you with to open the file (create, read only, write only etc). The following table lists the various file open attributes together with a broef description of each:

ModeDescription
rRead only access. Pointer is positioned at start of file.
r+Read and write access. Pointer is positioned at start of file.
wWrite only access. Pointer is positioned at start of file. File is created if it does not already exist.
w+Read and write access. Pointer is positioned at start of file. File is created if it does not already exist.
aWrite only access. Pointer is positioned at end of file. File is created if it does not already exist.
a+Read and write access. Pointer is positioned at end of file. File is created if it does not already exist.
xCreate and open for write only. Pointer is positioned at start of file. Return false if file already exists.
x+Create and open for read and write. Pointer is positioned at start of file. Return false if file already exists.