-1

I am using the nlist() function from PHPseclib to list the contents of a directory on a remote server. This is the result I get. Array ( [0] => newfile.txt [1] => . [2] => .. [3] => oldfile.txt [4] => ReadMe.pdf ).

I do have the following files in this folder.

1. newfile.txt
2. oldfile.txt
3. ReadMe.pdf

But, why is it putting the . and .. in the array? This seems to happen no matter what directory I am in or how many items are in that directory.

skjcyber
  • 5,759
  • 12
  • 40
  • 60
Shane A. Darr
  • 521
  • 6
  • 16

2 Answers2

2

. and .. are magic, and exist in every folder. The first refers to the current directory, the second refers to the parent directory.

You can remove them from the results list with http://php.net/array_diff

<?
$arr = array('newfile.txt', '.', '..', 'oldfile.txt', 'readme.pdf');
$arr = array_diff($arr, array('.', '..'));
print_r($arr)
?>
Dan
  • 4,312
  • 16
  • 28
1

Under Unix-like systems, all directories contain two additional entries. . refers to the current directory and .. refers to the parent directory.

You could use array_filter to remove these items from your array:

$files = nlist($dir = '/path/to/directory/');
$array = array_filter($files, function($file) {
    return $file[0] !== '.'; // return if filename doesn't start with period
});
Amal Murali
  • 75,622
  • 18
  • 128
  • 150