[991]PHP網站開發 進階應用技巧2
<?php
$base_dir="D:/xampplite/htdocs/08/test/uploads";
$base_url="http://localhost/08/test/uploads";
$dir=(empty($_REQUEST['to']))?$base_dir:str_replace("\\","/",realpath($_REQUEST['to']));
$dir=(ereg("^".$base_dir,$dir))?$dir:$base_dir;
$url=str_replace($base_dir,$base_url,$dir);
define("_UPLOAD_DIR",$dir);
define("_UPLOAD_URL",$url);
if($_GET['op']=="del"){
$file=mb_convert_encoding($_GET['file'], "Big5", "Big5,UTF-8");
@unlink(_UPLOAD_DIR."/".$file);
header("location:"._UPLOAD_DIR);
}elseif($_POST['op']=="del"){
foreach($_POST['files'] as $file){
$file=mb_convert_encoding($file, "Big5", "Big5,UTF-8");
@unlink(_UPLOAD_DIR."/".$file);
}
header("location:"._UPLOAD_DIR);
}
$dh=opendir(_UPLOAD_DIR);
$main="
<form action='{$_SERVER['PHP_SELF']}' method='post'>
<table class='tinytable'>
<tr><td colspan=4>$dir</td></tr>
<tr><th>檔名</th><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><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><td>
<input type='checkbox' name='files[]' value='$file'>
<a href='{$_SERVER['PHP_SELF']}?file=$file&op=del&to="._UPLOAD_DIR."'>刪除</a></td></tr>";
}
$main.="
<tr><th colspan=4>
<input type='hidden' name='to' value='"._UPLOAD_DIR."'>
將勾選的檔案 <input type='radio' name='op' value='del'>刪除
<input type='submit' value='送出'>
</th></tr>
</table>
</form>";
?>
<!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];
}
?>