The function of this code is to list files in a directory, however with a mysterious error.
The problem is the following, when it has only one file inside the folder, it shows the file and shows a folder with the same name, or when it has more than one file, it shows only a single file and shows a folder with the same name.When you have only one file:
Whenyouhavemorethanonefile:
<?php
error_reporting(1);
/***[ CONFIGURAÇÕES ]***/
// Definir propriedades de classificação.
$sort = array(
array('key'=>'lname', 'sort'=>'asc'), // ... isso define a classificação inicial "coluna" e ordem ...
array('key'=>'size', 'sort'=>'asc') // ... para itens com o mesmo valor de classificação inicial, classifique dessa maneira.
);
// Os arquivos que você deseja ocultar formam a listagem
$ignore_list = array('');
/***[ LÓGICA DE DIRETÓRIO ]***/
// Obter esta pasta e nome de arquivos.
$this_script = basename(__FILE__);
$this_folder = str_replace('/'.$this_script, '', $_SERVER['SCRIPT_NAME']);
$this_domain = $_SERVER['SERVER_NAME'];
$dir_name = explode("/", $this_folder);
//$dir_name = explode("/",dirname($_SERVER['REQUEST_URI']))
//$dir_path = explode("/", $this_folder);
// Declare vars usados além deste ponto.
$file_list = array();
$folder_list = array();
$total_size = 0;
$filetype = array(
'doc' => array('doc','docs','docx','pptx','pdf','pages','key','numbers','xls','ppt','odt','ods','odp','odg','odc','odi','xml','x-office-document'),
'text' => array('txt', 'rtf', 'text', 'nfo', 'md', 'markdown'),
'iso' => array('iso'),
'audio' => array('aac', 'mp3', 'wav', 'wma', 'm4p','spx', 'ogg', 'oga', 'midi', 'mid'),
'image' => array('ai', 'bmp', 'eps', 'gif', 'ico', 'jpg', 'jpeg', 'png', 'psd', 'psp', 'raw', 'tga', 'tif', 'tiff','icns'),
'video' => array('mv4', 'bup', 'mkv', 'ifo', 'flv', 'vob', '3g2', 'bik', 'xvid', 'divx', 'wmv', 'avi', '3gp', 'mp4', 'mov', '3gpp', '3gp2', 'swf', 'mpg', 'ogv','x-shockwave-flash','mpeg'),
'archive' => array('7z', 'dmg', 'rar', 'sit', 'zip', 'bzip', 'gz', 'tar','pkg','safariextz','bz2','bz','deb', 'x-compressed-tar'),
'app' => array('ipa', 'exe', 'msi', 'mse', 'app'),
'script' => array('js', 'html', 'htm', 'xhtml', 'jsp', 'asp', 'aspx', 'php', 'xml', 'css', 'plist', 'sh', 'bat'),
'torrent' => array('torrent')
);
// Abra o diretório atual...
if ($handle = opendir('.'))
{
// ...comece a digitalizar através dele.
while (false !== ($file = readdir($handle)))
{
// Certifique-se de que não listamos esta pasta, arquivo ou seus links.
if ($file != "." && $file != ".." && $file != $this_script && !in_array($file, $ignore_list))
{
// Obter informações sobre o arquivo
$stat = stat($file); // ... lento, mas mais rápido que usando filemtime () & filesize ().
$info = pathinfo($file);
// Organize as informações do arquivo.
$item['name'] = $info['filename'];
$item['lname'] = strtolower($info['filename']);
$item['ext'] = $info['extension'];
$item['lext'] = strtolower($info['extension']);
if($info['extension'] == '') $item['ext'] = '.';
if(in_array($item[lext], $filetype['doc'])){
$item['class'] = 'type-document';
}elseif(in_array($item[lext], $filetype['text'])){
$item['class'] = 'type-text';
}elseif(in_array($item[lext], $filetype['iso'])){
$item['class'] = 'type-iso';
}elseif(in_array($item[lext], $filetype['audio'])){
$item['class'] = 'type-audio';
}elseif(in_array($item[lext], $filetype['image'])){
$item['class'] = 'type-image';
}elseif(in_array($item[lext], $filetype['video'])){
$item['class'] = 'type-video';
}elseif(in_array($item[lext], $filetype['archive'])){
$item['class'] = 'type-archive';
}elseif(in_array($item[lext], $filetype['app'])){
$item['class'] = 'type-app';
}elseif(in_array($item[lext], $filetype['script'])){
$item['class'] = 'type-script';
}elseif(in_array($item[lext], $filetype['torrent'])){
$item['class'] = 'type-torrent';
}else{
$item['class'] = 'type-generic';
}
$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);
}
// Limpar cache stat () para liberar memória (não é realmente necessário).
clearstatcache();
// Adicione este tamanho de arquivo de itens ao tamanho total desta pasta
$total_size += $item['bytes'];
}
}
// Feche o diretório quando terminar.
closedir($handle);
}
// Ordenar lista de pastas.
if($folder_list)
$folder_list = php_multisort($folder_list, $sort);
// Ordenar lista de arquivos.
if($file_list)
$file_list = php_multisort($file_list, $sort);
// Calcular o tamanho total da pasta (correção: o tamanho total não pode ser exibido enquanto não houver pasta dentro do diretório)
if($file_list && $folder_list || $file_list)
$total_size = bytes_to_string($total_size, 2);
$total_folders = count($folder_list);
$total_files = count($file_list);
if ($total_folders > 0){
if ($total_folders > 1){
$funit = 'pastas';
}else{
$funit = 'pasta';
}
$contained = $total_folders.' '.$funit;
}
if ($total_files > 0){
if($total_files > 1){
$iunit = 'itens';
}else{
$iunit = 'item';
}
if (isset($contained)){
$contained .= ' & '.$total_files.' '.$iunit;
}else{
$contained = $total_files.' '.$iunit;
}
}
/**
* http://us.php.net/manual/en/function.array-multisort.php#83117
*/
function php_multisort($data,$keys)
{
foreach ($data as $key => $row)
{
foreach ($keys as $k)
{
$cols[$k['key']][$key] = $row[$k['key']];
}
}
$idkeys = array_keys($data);
$i=0;
foreach ($keys as $k)
{
if($i>0){$sort.=',';}
$sort.='$cols['.$k['key'].']';
if($k['sort']){$sort.=',SORT_'.strtoupper($k['sort']);}
if($k['type']){$sort.=',SORT_'.strtoupper($k['type']);}
$i++;
}
$sort .= ',$idkeys';
$sort = 'array_multisort('.$sort.');';
eval($sort);
foreach($idkeys as $idkey)
{
$result[$idkey]=$data[$idkey];
}
return $result;
}
/* START / INICIO [ SIZE / TAMANHO ]
@ http://us3.php.net/manual/en/function.filesize.php#84652 */
function bytes_to_string($size, $precision = 0) {
$sizes = array('YB', 'ZB', 'EB', 'PB', 'TB', 'GB', 'MB', 'KB', 'Bytes');
$total = count($sizes);
while($total-- && $size > 1024) $size /= 1024;
$return['num'] = round($size, $precision);
$return['str'] = $sizes[$total];
return $return;
}
/* END / FIM [ SIZE / TAMANHO ] */
/* START / INICIO [ TIME / TEMPO ]
@ http://us.php.net/manual/en/function.time.php#71342
@ https://pt.stackoverflow.com/questions/295389/plural-em-time-ago */
function time_ago($timestamp, $recursive = 0)
{
$current_time = time();
$difference = $current_time - $timestamp;
$periods = array("segundo", "minuto", "hora", "dia", "semana", "m", "ano", "década");
$lengths = array(1, 60, 3600, 86400, 604800, 2630880, 31570560, 315705600);
for ($val = sizeof($lengths) - 1; ($val >= 0) && (($number = $difference / $lengths[$val]) <= 1); $val--);
if ($val < 0) $val = 0;
$new_time = $current_time - ($difference % $lengths[$val]);
$number = floor($number);
if($number == 1 && $val == 5)
{
$periods[$val] .= "ês";
}
else if($number != 1 && $val == 5)
{
$periods[$val] .= "eses";
}
else if($number != 1)
{
$periods[$val] .= "s";
}
$text = sprintf("%d %s atrás", $number, $periods[$val]);
if (($recursive == 1) && ($val >= 1) && (($current_time - $new_time) > 0))
{
$text .= time_ago($new_time);
}
return $text;
}
/* END / FIM [ TIME / TEMPO ] */
/* START / INICIO [ TRANSLATION / TRADUÇÃO ]
@ Send translations to <[email protected]> */
$translation["english"] = array(
"name_mod" => "file name",
"size_mod" => "size",
"date_mod" => "file date",
"create_dir" => "Create Directory",
"upload_dir" => "Upload"
);
$translation["portugues"] = array(
"name_mod" => "nome dos arquivos",
"size_mod" => "tamanho",
"date_mod" => "data de modificação",
"create_dir" => "Criar pasta",
"upload_dir" => "Upload"
);
// DEFINIR TRADUÇÃO PADRÃO.
$language = "portugues";
if (!isset($translation[$language]))
$language = "english";
$_ = $translation[$language];
/* END / FIM [ TRANSLATION / TRADUÇÃO ] */
?>
<!--[ TEMPLATE HTML ]-->
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Dashboard</title>
<link rel="icon" href="img/favicon.ico">
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div id="wrapper">
<header>
<img src="img/logo.png">
<h3>
<a href=".." onclick="return confirm('Você tem certeza que deseja voltar?')">Página Inicial</a> / <a href=".">Default</a>
</h3>
</header>
<ul id="list">
<li class="header">
<span class="name"><?=sprintf($_['name_mod']);?></span>
<span class="size"><?=sprintf($_['size_mod']);?></span>
<span class="time"><?=sprintf($_['date_mod']);?></span>
</li>
<!-- PASTAS -->
<? if($folder_list): ?>
<? foreach($folder_list as $item) : ?>
<li class="folder">
<span class="name">
<a href="<?=$item['name']?>/"><?=$item['name']?></a>
</span>
<span class="size">-</span>
</li>
<? endforeach; ?>
<? endif; ?>
<!-- /PASTAS -->
<!-- ARQUIVOS -->
<? if($file_list): ?>
<? foreach($file_list as $item) : ?>
<li class="file <?=$item['class']?>">
<span class="name">
<a href="<?=$item['name']?>.<?=$item['ext']?>"><?=$item['name']?>.<?=$item['ext']?></a>
</span>
<span class="size"><?=$item['size']['num']?>
<em><?=$item['size']['str']?></em>
</span>
<span class="time"><?=time_ago($item['mtime'])?></span>
</li>
<? endforeach; ?>
<? endif; ?>
<!-- /ARQUIVOS -->
<? if($file_list): ?>
<li class="footer"><?=$contained?>, <?=$total_size['num']?> <?=$total_size['str']?> de tamanho</li>
<? endif; ?>
</ul>
</div>
</body>
</html>