Difference between revisions of "PHP, Filesystems and File I/O"
(→Deleting Directories in PHP) |
m (→Moving, Copying and Deleting Files with PHP) |
||
Line 123: | Line 123: | ||
?> | ?> | ||
</pre> | </pre> | ||
+ | |||
+ | == Accessing File Attributes == | ||
+ | |||
+ | PHP provides access to a wide range of file attributes such as when the file was created, whether the file is readable or writeable and the current file size. | ||
+ | |||
+ | The PHP ''stat()'' and ''fstat()'' functions provide a wealth of information about a file. The information is so copious that the results are returned as an associative array. The function take a single argument. ''stat()'' takes a string definingthe poath to the file. ''fstat()'' takes a file handle returned from an ''fopen()'' function call. | ||
+ | |||
+ | The following table outlines the array values returned by both functions: | ||
+ | |||
+ | <table border="1" cellspacing="0" width="100%"> | ||
+ | <tr style="background:#efefef;"> | ||
+ | <th>Key<th>Description</th> | ||
+ | <tr> | ||
+ | <td>dev<td>Device number</td> | ||
+ | <tr> | ||
+ | <td>ino<td>Inode number</td> | ||
+ | <tr> | ||
+ | <td>mode<td>Inode protection mode</td> | ||
+ | <tr> | ||
+ | <td>nlink<td>Number of links</td> | ||
+ | <tr> | ||
+ | <td>uid<td>User ID of owner</td> | ||
+ | <tr> | ||
+ | <td>gid<td>Group ID of owner</td> | ||
+ | <tr> | ||
+ | <td>rdev<td>Inode device type</td> | ||
+ | <tr> | ||
+ | <td>size<td>Size in bytes</td> | ||
+ | <tr> | ||
+ | <td>atime<td>Last access (Unix timestamp)</td> | ||
+ | <tr> | ||
+ | <td>mtime<td>Last modified (Unix timestamp)</td> | ||
+ | <tr> | ||
+ | <td>ctime<td>Last inode change (Unix timestamp)</td> | ||
+ | <tr> | ||
+ | <td>blksize<td>Blocksize of filesystem IO (platform dependent)</td> | ||
+ | <tr> | ||
+ | <td>blocks<td>Number of blocks allocated</td> | ||
+ | </table> |
Revision as of 17:20, 5 June 2007
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 server filesystem root, not your web server 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:
Mode | Description |
---|---|
r | Read only access. Pointer is positioned at start of file. |
r+ | Read and write access. Pointer is positioned at start of file. |
w | Write 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. |
a | Write 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. |
x | Create 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. |
Closing Files in PHP
Once a file has been opened it can closed using the fclose function. The fclose function takes a single argument; the file handle returned by the fopen function when the file was first opened.
Given this information we can write a script to open a file. For the purposes of this example we will create a new file in the root of our web server. We will open the file in w+ mode so that it will created if it does not already exist and provide both read and write access. We will then close the file using fclose():
<?php $fileHandle = fopen('/tmp/php_essentials.txt', 'w+') OR die ("Can't open file\n"); fclose ($fileHandle); ?>
Writing to a File using PHP
Having created and opened the file the next task is to write data to the file. We can do this using the PHP fwrite and fputs functions. These are essentially tyhe same function so either can be used.
fwrite takes two arguments, the file handle returned form the orginal fopen and he string to be written. We can, therefore extend our example to write a string to our file:
<?php $fileHandle = fopen('/tmp/php_essentials.txt', 'w+') OR die ("Can't open file\n"); $result = fwrite ($fileHandle, "This line of text was written by PHP\n"); if ($result) { echo "Data written successfully.<br>"; } else { echo "Data write failed.<br>"; } fclose($fileHandle); ?>
After running the above script you should find a file exists on your server containing the line This line of text was written by PHP.
Reading From a File using PHP
Data can be read from a file using the PHP fread() function. fread accepts two arguments, the file handle and the number of bytes to be read from the file:
<?php $fileHandle = fopen('/tmp/php_essentials.txt', 'w+') OR die ("Can't open file\n"); fwrite ($fileHandle, "This line of text was written by PHP\n"); fclose($fileHandle); $fileHandle = fopen('/tmp/php_essentials.txt', 'r') OR die ("Can't open file\n"); $fileData = fread ($fileHandle, 1024); echo "data = $fileData"; fclose($fileHandle); ?>
The above example should generate the following output:
data = This line of text was written by PHP done
It is also possible to read the contents of an enter file with the readfile function. This function reads the entire contents of a file and outputs that content. Assumign you don't need to do anything but output the contents of a file then 'readfile is an easy solution because it does all the work for you. You do not need to open the file, read the data, close the file and display the data. All you need to do is call readfile and it does the rest.
Checking Whether a File Exists
The file_exists fuinction can be used at any time to find if a file already exists in the file system. The function takes a single argument - the path to the file in question and returns a boolean true or false value depending on whether the existance of the file.
Moving, Copying and Deleting Files with PHP
Files can be copied uysing the copy function, renamed using the rename function and deleted using the unlink function. For example we can perform a number tasks on our example file:
<?php if (file_exists('/tmp/php_essentials.txt) { copy ('/tmp/php_essentials.txt, '/tmp/php_essentials.bak'); // Copy the file rename ('/tmp/php_essentials.bak', '/tmp/php_essentials.old'); // Rename the file unlink ('/tmp/php_essentials.old'); // Delete the file } ?>
Accessing File Attributes
PHP provides access to a wide range of file attributes such as when the file was created, whether the file is readable or writeable and the current file size.
The PHP stat() and fstat() functions provide a wealth of information about a file. The information is so copious that the results are returned as an associative array. The function take a single argument. stat() takes a string definingthe poath to the file. fstat() takes a file handle returned from an fopen() function call.
The following table outlines the array values returned by both functions:
Key | Description |
---|---|
dev | Device number |
ino | Inode number |
mode | Inode protection mode |
nlink | Number of links |
uid | User ID of owner |
gid | Group ID of owner |
rdev | Inode device type |
size | Size in bytes |
atime | Last access (Unix timestamp) |
mtime | Last modified (Unix timestamp) |
ctime | Last inode change (Unix timestamp) |
blksize | Blocksize of filesystem IO (platform dependent) |
blocks | Number of blocks allocated |