[991]PHP網站開發 進階應用技巧2

10-1 index.php

<?php
//基本路徑
$base_dir="D:/xampplite/htdocs/10/test/uploads";

//基本網址
$base_url="http://localhost/10/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=$_GET['file'];
    @unlink(_UPLOAD_DIR."/".$file);
    header("location:"._UPLOAD_DIR);
//刪除多檔案
}elseif($_POST['op']=="del"){
    if(is_array($_POST['files'])){
    foreach($_POST['files'] as $file){
        @unlink(_UPLOAD_DIR."/".$file);
    }
    header("location:"._UPLOAD_DIR);
    }
//搬移多檔案
}elseif($_POST['op']=="move"){
    if(is_array($_POST['files'])){
    foreach($_POST['files'] as $file){
        @rename(_UPLOAD_DIR."/".$file,$_POST['new_dir']."/".$file);
    }
    header("location:"._UPLOAD_DIR);
  }


//搬移目錄
}elseif($_POST['op']=="move_dir"){
    $dirname=basename(_UPLOAD_DIR); 
  rename(_UPLOAD_DIR,$_POST['new_dir2']."/{$dirname}");
  header("location:index.php?to=".$_POST['new_dir2']);

//刪除目錄
}elseif($_GET['op']=="del_dir"){
     $dirname=dirname(_UPLOAD_DIR);
  deltree(_UPLOAD_DIR);
  header("location:index.php?to=".$dirname);


//複製目錄
}elseif($_POST['op']=="copy_dir"){
    $dirname=basename(_UPLOAD_DIR); 
  full_copy(_UPLOAD_DIR,$_POST['new_dir2']."/{$dirname}_copy");
  header("location:index.php?to=".$_POST['new_dir2']);

//目錄改名 
}elseif(!empty($_POST['new_dir_name'])){
  $dirname=dirname(_UPLOAD_DIR); 
  rename(_UPLOAD_DIR,$dirname."/".$_POST['new_dir_name']);
  header("location:index.php?to=".$dirname);

}elseif(!empty($_POST['mk_dir'])){
    mk_dir(_UPLOAD_DIR."/".$_POST['mk_dir']);
  header("location:"._UPLOAD_DIR);
}elseif(!empty($_FILES['pic']['tmp_name'])){
  foreach($_FILES['pic']['tmp_name'] as $i => $tmpname){
    move_uploaded_file($tmpname , _UPLOAD_DIR."/{$_FILES['pic']['name'][$i]}");
  }
}


//開啟目錄
$dh=opendir(_UPLOAD_DIR);

$main="
<script src='js/jquery-1.3.2.min.js' type='text/javascript'></script>
<script src='js/jquery.MultiFile.js' type='text/javascript'></script>

<form action='{$_SERVER['PHP_SELF']}' method='post' enctype='multipart/form-data'>
<table style='width:1000px;' class='tinytable'>
<tr><td style='width:400px;'>

<div style='height:400px;overflow:auto;'>
    <table class='tinytable' style='width:100%;'>
    <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;
        }
    }

    //秀出目錄
    if(is_array($dir_arr)){
        foreach($dir_arr as $sub_dir){
            $size=($sub_dir=="..")?"":dirSize(_UPLOAD_DIR."/".$sub_dir);
            $size=($sub_dir=="..")?"":formatBytes($size,1);
            $del=($sub_dir=="..")?"":"<a href='index.php?op=del_dir&to="._UPLOAD_DIR."/".$sub_dir."'>刪除</a>";
            $main.= "<tr><td><a href='index.php?to="._UPLOAD_DIR."/".$sub_dir."'>$sub_dir</a></td><td>$size</td><td>目錄</td><td>$del</td></tr>";
        }
    }

    //秀出檔案
    if(is_array($file_arr)){
        foreach($file_arr as $file){
            $size=filesize(_UPLOAD_DIR."/".$file);
            $size=formatBytes($size,1);  
            $exif=(strtolower(substr($file,-3))=="jpg")?" (<a href='exif.php?file="._UPLOAD_DIR."/{$file}#' target='show'>exif</a>)":"";
            $main.= "<tr><td><a href='"._UPLOAD_URL."/{$file}'  target='show'>$file</a>$exif</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.="
    </table>
</div>


</td><td><iframe name='show' style='width:100%;height:400px;border:1px solid gray;'></iframe></td></tr>

<tr><th colspan=2>

<input type='hidden' name='to' value='"._UPLOAD_DIR."'>

        將「"._UPLOAD_DIR."」<input type='radio' name='op' value='move_dir'>搬移<input type='radio' name='op' value='copy_dir'>複製到:".folder_select($base_dir,"new_dir2")."或改名為<input type='text' name='new_dir_name' size=10><br>

    將勾選的檔案 <input type='radio' name='op' value='del'>刪除
    <input type='radio' name='op' value='move'>搬移到:".folder_select($base_dir,"new_dir")."
    建立新目錄:<input type='text' name='mk_dir'><br>
    ,上傳檔案:<input type='file' name='pic[]' class='multi' />
    <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=Big5">
  <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];
}


//目錄選單
function folder_select($base_dir="",$name="",$i=0){
  $prefix=str_repeat("--",$i);
  $i++;
  $disabled=(_UPLOAD_DIR==$base_dir)?"disabled":"";
  $option=($i==1)?"<option value='{$base_dir}/' $disabled>/</option>\n":"";
  $dh=opendir($base_dir);
  while($file=readdir($dh)){
    if($file=="." or $file=="..")continue;
    $type=filetype($base_dir."/".$file);
    if($type=="dir"){
            $disabled=(_UPLOAD_DIR=="{$base_dir}/{$file}")?"disabled":"";
        $option.="<option value='{$base_dir}/{$file}' $disabled>{$prefix}{$file}</option>\n";
        $option.=folder_select("{$base_dir}/{$file}",$name,$i);
    }
    }
    if($i==1){
        $main="<select name='$name'>
        $option
        </select>";
    }else{
    $main=$option;
    }
    return $main;
}


//建立目錄
function mk_dir($dir=""){
    //若無目錄名稱秀出警告訊息
    if(empty($dir))die("沒有目錄名稱");
    //若目錄不存在的話建立目錄
    if (!is_dir($dir)) {
        umask(000);
        //若建立失敗秀出警告訊息
        if(!mkdir($dir, 0777)){
            die("$dir 建立失敗!");
        }
    }
}

 


//目錄複製
function full_copy( $source, $target ){
    if ( is_dir( $source ) ){
        @mkdir( $target );

        $d = dir( $source );

        while ( FALSE !== ( $entry = $d->read() ) ){
            if ( $entry == '.' || $entry == '..' ){
                continue;
            }

            $Entry = $source . '/' . $entry;
            if ( is_dir( $Entry ) ){
                full_copy( $Entry, $target . '/' . $entry );
                continue;
            }
            copy( $Entry, $target . '/' . $entry );
        }

        $d->close();
    }else{
        copy( $source, $target );
    }
}

//刪除整個目錄
function delTree($dir) {
    $files = glob( $dir . '*', GLOB_MARK );
    foreach( $files as $file ){
        if( is_dir( $file ) )
            delTree( $file );
        else
            unlink( $file );
    }

    if (is_dir($dir)) rmdir( $dir );

}
?>