PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!
// Get this folder and files name.
$this_script = basename(__FILE__);
$this_folder = str_replace('/'.$this_script, '', $_SERVER['SCRIPT_NAME']);
// Declare vars used beyond this point.
$file_list = array();
$folder_list = array();
$total_size = 0;
// Open the current directory...
if ($handle = opendir('.'))
{
// ...start scanning through it.
while (false !== ($file = readdir($handle)))
{
// Make sure we don't list this folder, file or their links.
if ($file != "." && $file != ".." && $file != $this_script && $file != ".DS_Store")
{
// Get file info.
$stat = stat($file); // ... slow, but faster than using filemtime() & filesize() instead.
$info = pathinfo($file);
// Organize file info.
$item['name'] = $info['filename'];
$item['lname'] = strtolower($info['filename']);
$item['ext'] = $info['extension'];
if($info['extension'] == '') $item['ext'] = '.';
$item['bytes'] = $stat['size'];
$item['size'] = bytes_to_string($stat['size'], 2);
$item['mtime'] = $stat['mtime'];
// Add files to the file list...
if($info['extension'] != '')
{
array_push($file_list, $item);
}
// ...and folders to the folder list.
else
{
array_push($folder_list, $item);
}
// Clear stat() cache to free up memory (not really needed).
clearstatcache();
// Add this items file size to this folders total size
$total_size += $item['bytes'];
}
}
But instead of listing the contents of the current directory I'd like to list the contents of a sub directory labelled 'uploads'. I also still need the anchor links on each file to link to their location in the sub directory.
Can anyone suggest how I can include a variable/constant to specify the sub directory and output & link it's contents?
$upload_dir = './uploads/';
if ($handle = opendir($upload_dir))
The only problem I found however was that this then messed up the file size and date data. Every file in the directory displayed as 0 bytes and 3 decades old. By adding this variable to the $stat and $info variables like this:
// Get file info.
$stat = stat($upload_dir.$file);
$info = pathinfo($upload_dir.$file);
It then corrected the size and date info. However the file links don't point to the upload directory. The path up to the site root is correct but it just doesn't add in the extra directory. Which bit do I need to change (presumably by appending the $upload_dir variable)?
Thanks for the info. I've made the changes to $stat and $info but no change. The output is as before and the links still don't include the '/uploads/' directory in the path.
In the HTML the following outputs the list of files:
In the anchor link it just seems to be linking to the filename of the item of the array and not injecting the path info. Where and how is it best to insert the path info including the $upload_dir?