Working with directories - Page 6
August 19, 2002
At the same time as working with files, you're often going to
want to work with directories as well. PHP's directory functions
are equally flexible and easy to use. The getcwd() function
(standing for "get current working directory") returns the current
directory:
string getcwd()
You can change the current directory by using the chdir()
function:
int chdir(string directory)
The opendir() and readdir() functions are used to
open and read the contents of a directory respectively. :
int opendir(string path)
The openddir() function returns a directory handle, which is
used when reading from the directory.
string readdir(int directory_handle)
When first called, readdir() returns the name of the first entry
in the directory. On subsequent calls it returns the following
entries in the directory until reaching the end, in which case it
will return false. Finally, the closedir() function closes the
directory, freeing up all resources tied up in keeping it open
(as happens with files too):
void closedir(directory_handle)
There are also two other commonly-used functions for creating and
removing directories - mkdir() for creating a directory,
and rmdir() for removing it:
bool mkdir(string directory_name [, int mode])
The mode integer is only used on Unix, and is used to set
the file directory
permissions. It
always starts with '0', followed by the usual three digits for
the owner, group and world permissions.
bool rmdir(string directory_name)
Both these fucnctions return TRUE if the operation succeeded, and
FALSE if not.
Putting it all together - traversing a directory tree
The next script traverses a directory tree, displaying all the
available files.
<?
function read_directory($directory) {
print "Directory: $directory<br>";
$dir = opendir($directory);
while ($file = readdir($dir)) {
if (is_file("$file")) {
print "--File: $file<br>";
}
elseif (is_dir($file) and ($file!='.') and ($file !='..')) {
read_directory($file);
}
}
closedir($dir);
}
$directory = getcwd();
read_directory($directory);
?>
Uploading Files
Working with and creating files directly on the server is not all
you can do with files - often you'll want to upload them from a
web page. There are other methods, but the most common is to
insert the data from an HTML form and POST the data, such as the
following:
<html>
<head><title>Uploading a file onto the server</title></head>
<body>
<form action='save_file.php' method='POST' enctype='multipart/form-data'>
<input type="hidden" name="MAX_FILE_SIZE" value="10000">
Select file to upload:
<input type='file'
name='uploadfile'>
<input type='submit'
value='Upload file'>
</form>
</body>
</html>
Some things to notice here - the form has an attribute
enctype=multipart/form-data. The input element is
type='file'.There is also a MAX_FILE_SIZE element
which ensures the user cannot attempt to upload a file of greater
than 10000 bytes. You should always check this limit in the script
as well, as it's easy to simulate this page without a limit.
Once the user clicks the submit button, the file is uploaded onto
the server into a temporary file in the default temporary directory
(unless you specify a different location in the php.ini, using
the upload_tmp_dir directive. Once the script processing
the form completes, the temporary file is removed (which prevents
people overwhelming your server with unwanted files), so your
script needs to specifically deal with the expected file.
Details about the uploaded file can be accessed with the
$_FILES associative array (PHP versions before 4.1 had to
use $HTTP_POST_FILES). It contains the following elements:
- $_FILES['uploadfile']['name']:
The file name from the client machine
- $_FILES['uploadfile']['size']The file size, in bytes
- $_FILES['uploadfile']['type']The file mime type
- $_FILES['uploadfile']['tmp_name']
The temporary name assigned to the file on the server
The move_uploaded_file() function takes the temporary name
of the file and a destination as arguments, and moves the file
from its temporary location to the new location.
bool move_uploaded_file ( string filename, string destination)
This function returns TRUE if the file is moved successfully, or
FALSE if the move failed for some reason (the file was not uploaded
in the first place, or could not be written to the new directory).
The following script is all you need to take an uploaded file,
and place it elsewhere on your server:
<?
// always check the file size - here it's set to a max of 10000 bytes
if ($_FILES['uploadfile']['size'] <=10000) {
$tmp_name = $_FILES['uploadfile']['tmp_name'];
$new_name = "/home/ian/".$_FILES['uploadfile']['name'];
if (move_uploaded_file($tmp_name, $new_name)) {
print "File successfully uploaded to $new_name";
}
else {
print "The file was not successfully uploaded to $new_name";
}
}
else {
print "File is too large to upload - please upload a smaller file";
}
?>
One thing that often goes wrong is that your script may not have
the correct permissions to write to where you're trying to write
to.
These two articles should have given you a good idea of the power
and flexibility of working with files in PHP. As always, the only
way to really master the topic is to experiment on your own. There
are other functions that we have not covered here which you may
find useful. Good luck!
Resources
Official PHP site
WDVL: PHP
WDVL: PHP Resources
PHPBuilder
Navigating within Files - Page 5
Handling files with PHP4 - Part1
|