Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP scandir and relative path

Tags:

php

scandir

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?

like image 895
John Avatar asked Jan 24 '26 03:01

John


1 Answers

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.

like image 105
Antonios Chasouras Avatar answered Jan 26 '26 16:01

Antonios Chasouras