Uploading Files and Navigating Directories in PHP - Navigating Directories
(Page 4 of 4 )
Before we start with the next section, please make sure that you are familiar with file permissions. Pretty much everything in the File Permissions section applies to the directories. To navigate through a directory, you begin by opening the directory with opdir() function:
$dir = opendir('directoryname');
As with reading and writing files, you create a pointer that can be referenced by the opened directory. To read the list of files within a directory you use the readdir() function, in a while loop:
while($thedir=readdir($dir)){
//write the file details here
}
and then you finally close the open directory with the closedir() function:
closedir($dir);
Other functions that we are going to use include:
filesize() function - gives you the size of the file in bytes.
filetime() - retrieves the modification time of a file.
Both of these functions are going to help us to create a directory listing.
Let's build a script that will show us the insides of a directory listing:
Script: browsedir.php
This script will list file names, file size and modification dates:
<html>
<head>
<title>Browse Directories</title>
</head>
<body>
<p>Browsing</p>
<?php
$current_dir = '.';
$dir = opendir($current_dir);
echo "Current directory is <b>$current_dir</b><br />";
echo' <table width="100%" border="0" cellspacing="1">
<tr>
<td width="34%"><b>File Name</b> </td>
<td width="26%"> <b>File Size </b></td>
<td width="40%"><b>Last Modified</b> </td>
</tr>';
while ($file = readdir($dir))
{
$fs=filesize($file);
$moddate=date('F j, Y',filemtime($file));
echo ' <tr>
<td>'.$file.'</td>
<td>'.$fs. ' bytes</td>
<td>'.$moddate.'</td>';
}
closedir($dir);
?>
</tr>
</table>
</body>
</html>

Fig5. Shows a list of all the files in the current directory, represented here by a dot(.)
Conclusion
This concludes our file and directory handling exploration.
| DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware. |