Класс для вывода файлов в текущей (можно изменить) директории
<?php
/**
* Class DirFileLister
*/
class DirFileLister
{
protected $dir;
protected $currentList;
/**
* DirFileLister constructor.
* @param string $dir
*/
public function __construct($dir = __DIR__)
{
$this->setDir($dir);
$this->scan();
}
/**
* @param string $dir
*/
public function setDir($dir)
{
$this->dir = $dir;
}
public function scan()
{
$this->clearList();
$items = scandir($this->dir);
if (!$items) return;
foreach ($items as $item) {
if (in_array($item, ['.'])) continue;
if (is_dir(__DIR__.'/'.$item)) {
$this->addDir($item);
continue;
}
if (is_file(__DIR__.'/'.$item)) {
$this->addFile($item);
}
}
}
/**
* @return array
*/
public function getDirs()
{
return $this->currentList['dirs'];
}
/**
* @return array
*/
public function getFiles()
{
return $this->currentList['files'];
}
/**
* @return array
*/
public function getDirsWithLinks()
{
$dirs = $this->getDirs();
foreach ($dirs as $key => $dir) {
$dirs[$key] = $this->makeLink($dir);
}
return $dirs;
}
/**
* @return array
*/
public function getFilesWithLinks()
{
$files = $this->getFiles();
foreach ($files as $key => $file) {
if (preg_match('/.*\.((php)|(htm)|(html))$/i', $file)) {
$files[$key] = $this->makeLink($file);
}
}
return $files;
}
protected function clearList()
{
$this->clearDirs();
$this->clearFiles();
}
protected function clearDirs()
{
$this->currentList['dirs'] = [];
}
protected function clearFiles()
{
$this->currentList['files'] = [];
}
protected function addDir($item)
{
$this->currentList['dirs'][] = $item;
}
protected function addFile($item)
{
$this->currentList['files'][] = $item;
}
/**
* @param string $item
* @return string
*/
protected function makeLink($item)
{
return '<a href="'.$item.'">'.$item.'</a>';
}
}
$lister = new DirFileLister();
foreach ($lister->getDirsWithLinks() as $item) {
echo $item.'<br/>';
}
foreach ($lister->getFilesWithLinks() as $item) {
echo $item.'<br/>';
}