I've tried all the solutions I read on here but can't seem to get this to work.
I'm trying to call scandir in this file: https://www.example.com/cms/uploader/index.php
to list all the files and directories in this folder: https://www.example.com/uploads/
I don't want to hardcode the example.com part because this will be different depending on the site. I've tried many combinations of: dirname(FILE), DIR, $_SERVER['SERVER_NAME'], and $_SERVER['REQUEST_URI'], etc. I either get a "failed to open dir, not implemented in..." error or nothing displays at all. Here is the code I'm using:
$directory = __DIR__ . '/../../uploads';
$filelist = "";
$dircont = scandir($directory);
foreach($dircont AS $item)
if(is_file($item) && $item[0]!='.')
$filelist .= '<a href="'.$item.'">'.$item.'</a>'."<br />\n";
echo $filelist;
What's the proper way to do this?
The $directory variable is set wrong. If you want to go 2 directories up use dirname() like this:
$directory = dirname(__DIR__,2) . '/uploads';
$filelist = "";
$dircont = scandir($directory);
foreach($dircont AS $item) {
if(is_file($item) && $item[0]!='.')
$filelist .= '<a href="'.$item.'">'.$item.'</a>'."<br />\n";
}
echo $filelist;
You can read more about scandir there is a section on how to use it with urls if allow_url_fopen is enabled but this is mainly in local/development environment.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With