[991]PHP網站開發 進階應用技巧2
<?php
if(!empty($_GET['to'])){
define("_UPLOAD_DIR",$_GET['to']);
}else{
define("_UPLOAD_DIR","D:/xampplite/htdocs/07/test/uploads");
}
define("_UPLOAD_URL","http://localhost/07/test/uploads");
$dh=opendir(_UPLOAD_DIR);
$main="<table class='tinytable'>
<tr><th>檔名</th><th>大小</th><th>類型</th></tr>";
while($file=readdir($dh)){
if($file==".")continue;
$type=filetype(_UPLOAD_DIR."/".$file);
if($type=="dir"){
$dir_arr[]=$file;
}else{
$file_arr[]=$file;
}
}
//秀出目錄
foreach($dir_arr as $sub_dir){
$size=($sub_dir=="..")?"":dirSize(_UPLOAD_DIR."/".$sub_dir);
$size=($sub_dir=="..")?"":formatBytes($size,1);
$sub_dir=mb_convert_encoding($sub_dir, "UTF-8", "Big5,UTF-8");
$main.= "<tr><td><a href='index.php?to="._UPLOAD_DIR."/".$sub_dir."'>$sub_dir</a></td><td>$size</td><td>目錄</td></tr>";
}
//秀出檔案
foreach($file_arr as $file){
$size=filesize(_UPLOAD_DIR."/".$file);
$size=formatBytes($size,1);
$file=mb_convert_encoding($file, "UTF-8", "Big5,UTF-8");
$main.= "<tr><td><a href='"._UPLOAD_URL."/{$file}'>$file</a></td><td>$size</td><td>檔案</td></tr>";
}
$main.="</table>";
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title></title>
<link rel="stylesheet" href="tinytable.css" />
<link rel="stylesheet" href="iconize_l.css" />
</head>
<body>
<?php echo $main;?>
</body>
</html>
<?php
//計算目錄大小
function dirSize($directory) {
$size = 0;
foreach(new RecursiveIteratorIterator(new RecursiveDirectoryIterator($directory)) as $file){
$size+=$file->getSize();
}
return $size;
}
//把 bytes 轉換成其他單位
function formatBytes($bytes, $precision = 2) {
$units = array('B', 'KB', 'MB', 'GB', 'TB');
$bytes = max($bytes, 0);
$pow = floor(($bytes ? log($bytes) : 0) / log(1024));
$pow = min($pow, count($units) - 1);
$bytes /= pow(1024, $pow);
return round($bytes, $precision) . ' ' . $units[$pow];
}
?>