phpMiniAdmin源码,mini mysql管理器,一段php代码搞定

代码语言:php

所属分类:其他

下面为部分代码预览,完整代码请点击下载或在bfwstudio webide中打开

<?php
/*
 PHP Mini MySQL Admin
 (c) 2004-2019 Oleg Savchuk <osalabs@gmail.com> http://osalabs.com
 Light standalone PHP script for quick and easy access MySQL databases.
 http://phpminiadmin.sourceforge.net
 Dual licensed: GPL v2 and MIT, see texts at http://opensource.org/licenses/
*/
$ACCESS_PWD=''; #!!!IMPORTANT!!! this is script access password, SET IT if you want to protect you DB from public access
#DEFAULT db connection settings
# --- WARNING! --- if you set defaults - it's recommended to set $ACCESS_PWD to protect your db!
$DBDEF=array(
'user'=>"",#required
'pwd'=>"", #required
'db'=>"",  #optional, default DB
'host'=>"",#optional
'port'=>"",#optional
'socket'=>"",#optional
'chset'=>"utf8",#optional, default charset
);
$IS_COUNT=false; #set to true if you want to see Total records when pagination occurs (SLOWS down all select queries!)
$DUMP_FILE=dirname(__FILE__).'/pmadump'; #path to file without extension used for server-side exports (timestamp, .sql/.csv/.gz extension added) or imports(.sql)
file_exists($f=dirname(__FILE__) . '/phpminiconfig.php')&&require($f); // Read from config (easier to update)
if (function_exists('date_default_timezone_set')) date_default_timezone_set('UTC');#required by PHP 5.1+
//constants
$VERSION='1.9.190822';
$MAX_ROWS_PER_PAGE=50; #max number of rows in select per one page
$D="\r\n"; #default delimiter for export
$BOM=chr(239).chr(187).chr(191);
$SHOW_D="SHOW DATABASES";
$SHOW_T="SHOW TABLE STATUS";
$DB=array(); #working copy for DB settings
$self=$_SERVER['PHP_SELF'];
session_set_cookie_params(0, null, null, false, true);
session_start();
if (!isset($_SESSION['XSS'])) $_SESSION['XSS']=get_rand_str(16);
$xurl='XSS='.$_SESSION['XSS'];
ini_set('display_errors',0);  #turn on to debug db or script issues
error_reporting(E_ALL ^ E_NOTICE);
//strip quotes if they set
if (get_magic_quotes_gpc()){
  $_COOKIE=array_map('killmq',$_COOKIE);
  $_REQUEST=array_map('killmq',$_REQUEST);
}
if ($_REQUEST['login']){
  if ($_REQUEST['pwd']!=$ACCESS_PWD){
    $err_msg="Invalid password. Try again";
  }else{
    $_SESSION['is_logged']=true;
    loadcfg();
  }
}
if ($_REQUEST['logoff']){
  check_xss();
  $_SESSION = array();
  savecfg();
  session_destroy();
  $url=$self;
  if (!$ACCESS_PWD) $url='/';
  header("location: $url");
  exit;
}
if (!$_SESSION['is_logged']){
  if (!$ACCESS_PWD) {
    $_SESSION['is_logged']=true;
    loadcfg();
  }else{
    print_login();
    exit;
  }
}
if ($_REQUEST['savecfg']){
  check_xss();
  savecfg();
}
loadsess();
if ($_REQUEST['showcfg']){
  print_cfg();
  exit;
}
//get initial values
$SQLq=trim(b64d($_REQUEST['q']));
$page=$_REQUEST['p']+0;
if ($_REQUEST['refresh'] && $DB['db'] && preg_match('/^show/',$SQLq) ) $SQLq=$SHOW_T;
if (db_connect('nodie')){
  $time_start=microtime_float();
  if ($_REQUEST['pi']){
    ob_start();phpinfo();$html=ob_get_clean();preg_match("/<body[^>]*>(.*?)<\/body>/is",$html,$m);
    $sqldr='<div class="pi">'.$m[1].'</div>';
  }else{
   if ($DB['db']){
    if ($_REQUEST['shex']){
     print_export();
    }elseif ($_REQUEST['doex']){
     check_xss();do_export();
    }elseif ($_REQUEST['shim']){
     print_import();
    }elseif ($_REQUEST['doim']){
     check_xss();do_import();
    }elseif ($_REQUEST['dosht']){
     check_xss();do_sht();
    }elseif (!$_REQUEST['refresh'] || preg_match('/^select|show|explain|desc/i',$SQLq) ){
     if ($SQLq)check_xss();
     do_sql($SQLq);#perform non-select SQL only if not refresh (to avoid dangerous delete/drop)
    }
   }else{
    if ( $_REQUEST['refresh'] ){
       check_xss();do_sql($SHOW_D);
    }elseif ($_REQUEST['crdb']){
      check_xss();do_sql('CREATE DATABASE `'.$_REQUEST['new_db'].'`');do_sql($SHOW_D);
    }elseif ( preg_match('/^(?:show\s+(?:databases|status|variables|process)|create\s+database|grant\s+)/i',$SQLq) ){
       check_xss();do_sql($SQLq);
    }else{
       $err_msg="Select Database first";
       if (!$SQLq) do_sql($SHOW_D);
    }
   }
  }
  $time_all=ceil((microtime_float()-$time_start)*10000)/10000;
  print_screen();
}else{
  print_cfg();
}
function do_sql($q){
 global $dbh,$last_sth,$last_sql,$reccount,$out_message,$SQLq,$SHOW_T;
 $SQLq=$q;
 if (!do_multi_sql($q)){
    $out_message="Error: ".mysqli_error($dbh);
 }else{
    if ($last_sth && $last_sql){
       $SQLq=$last_sql;
       if (preg_match("/^select|show|explain|desc/i",$last_sql)) {
          if ($q!=$last_sql) $out_message="Results of the last select displayed:";
          display_select($last_sth,$last_sql);
       } else {
         $reccount=mysqli_affected_rows($dbh);
         $out_message="Done.";
         if (preg_match("/^insert|replace/i",$last_sql)) $out_message.=" Last inserted id=".get_identity();
         if (preg_match("/^drop|truncate/i",$last_sql)) do_sql($SHOW_T);
       }
    }
 }
}
function display_select($sth,$q){
 global $dbh,$DB,$sqldr,$reccount,$is_sht,$xurl,$is_sm;
 $rc=array("o","e");
 $dbn=ue($DB['db']);
 $sqldr='';
 $is_shd=(preg_match('/^show\s+databases/i',$q));
 $is_sht=(preg_match('/^show\s+tables|^SHOW\s+TABLE\s+STATUS/',$q));
 $is_show_crt=(preg_match('/^show\s+create\s+table/i',$q));
 if ($sth===FALSE or $sth===TRUE) return;#check if $sth is not a mysql resource
 $reccount=mysqli_num_rows($sth);
 $fields_num=mysqli_field_count($dbh);
 $w='';
 if ($is_sm) $w='sm ';
 if ($is_sht || $is_shd) {$w='wa';
   $url='?'.$xurl."&db=$dbn";
   $sqldr.="<div class='dot'>
 MySQL Server:
 &#183; <a href='$url&q=".b64u("show variables")."'>Show Configuration Variables</a>
 &#183; <a href='$url&q=".b64u("show status")."'>Show Statistics</a>
 &#183; <a href='$url&q=".b64u("show processlist")."'>Show Processlist</a> ";
   if ($is_shd) $sqldr.="&#183; <label>Create new database: <input type='text' name='new_db' placeholder='type db name here'></label> <input type='submit' name='crdb' value='Create'>";
   $sqldr.="<br>";
   if ($is_sht) $sqldr.="Database: &#183; <a href='$url&q=".b64u("show table status")."'>Show Table Status</a>";
   $sqldr.="</div>";
 }
 if ($is_sht){
   $abtn="<div><input type='submit' value='Export' onclick=\"sht('exp')\">
 <input type='submit' value='Drop' onclick=\"if(ays()){sht('drop')}else{return false}\">
 <input type='submit' value='Truncate' onclick=\"if(ays()){sht('trunc')}else{return false}\">
 <input type='submit' value='Optimize' onclick=\"sht('opt')\">
 <b>selected tables</b></div>";
   $sqldr.=$abtn."<input type='hidden' name='dosht' value=''>";
 }
 $sqldr.="<div><table id='res' class='res $w'>";
 $headers="<tr class='h'>";
 if ($is_sht) $headers.="<td><input type='checkbox' name='cball' value='' onclick='chkall(this)'></td>";
 for($i=0;$i<$fields_num;$i++){
    if ($is_sht && $i>0) break;
    $meta=mysqli_fetch_field($sth);
    $headers.="<th><div>".hs($meta->name)."</div></th>";
 }
 if ($is_shd) $headers.="<th>show create database</th><th>show table status</th><th>show triggers</th>";
 if ($is_sht) $headers.="<th>engine</th><th>~rows</th><th>data size</th><th>index size</th><th>show create table</th><th>explain</th><th>indexes</th><th>export</th><th>drop</th><th>truncate</th><th>optimize</th><th>repair</th><th>comment</th>";
 $headers.="</tr>\n";
 $sqldr.=$headers;
 $swapper=false;
 while($row=mysqli_fetch_row($sth)){
   $sqldr.="<tr class='".$rc[$swp=!$swp]."' onclick='tc(this)'>";
   $v=$row[0];
   if ($is_sht){
     $vq='`'.$v.'`';
     $url='?'.$xurl."&db=$dbn&t=".b64u($v);
     $sqldr.="<td><input type='checkbox' name='cb[]' value=\"".hs($vq)."\"></td>"
     ."<td><a href=\"$url&q=".b64u("select * from $vq")."\">".hs($v)."</a></td>"
     ."<td>".hs($row[1])."</td>"
     ."<td align='right'>".hs($row[4])."</td>"
     ."<td align='right'>".hs($row[6])."</td>"
     ."<td align='right'>".hs($row[8])."</td>"
     ."<td>&#183;<a href=\"$url&q=".b64u("show create table $vq")."\">sct</a></td>"
     ."<td>&#183;<a href=\"$url&q=".b64u("explain $vq")."\">exp</a></td>"
     ."<td>&#183;<a href=\"$url&q=".b64u("show index from $vq")."\">ind</a></td>"
     ."<td>&#183;<a href=\"$url&shex=1&rt=".hs(ue($vq))."\">export</a></td>"
     ."<td>&#183;<a href=\"$url&q=".b64u("drop table $vq")."\" onclick='return ays()'>dr</a></td>"
     ."<td>&#183;<a href=\"$url&q=".b64u("truncate table $vq")."\" onclick='return ays()'>tr</a></td>"
     ."<td>&#183;<a href=\"$url&q=".b64u("optimize table $vq")."\" onclick='return ays()'>opt</a></td>"
     ."<td>&#183;<a href=\"$url&q=".b64u("repair table $vq")."\" onclick='return ays()'>rpr</a></td>"
     ."<td>".hs($row[$fields_num-1])."</td>";
   }elseif ($is_shd){
     $url='?'.$xurl."&db=".ue($v);
     $sqldr.="<td><a href=\"$url&q=".b64u("SHOW TABLE STATUS")."\">".hs($v)."</a></td>"
     ."<td><a href=\"$url&q=".b64u("show create database `$v`")."\">scd</a></td>"
     ."<td><a href=\"$url&q=".b64u("show table status")."\">status</a></td>"
     ."<td><a href=\"$url&q=".b64u("show triggers")."\">trig</a></td>";
   }else{
     for($i=0;$i<$fields_num;$i++){
      $v=$row[$i];
      if (is_null($v)) $v="<i>NULL</i>";
      elseif (preg_match('/[\x00-\x09\x0B\x0C\x0E-\x1F]+/',$v)){#all chars <32, except \n\r(0D0A)
       $vl=strlen($v);$pf='';
       if ($vl>16 && $fields_num>1){#show full dump if just one field
         $v=substr($v, 0, 16);$pf='...';
       }
       $v='BINARY: '.chunk_split(strtoupper(bin2hex($v)),2,' ').$pf;
      }else $v=hs($v);
      if ($is_show_crt) $v="<pre>$v</pre>";
      $sqldr.="<td><div>$v".(!strlen($v)?"<br>":'')."</div></td>";
     }
   }
   $sqldr.="</tr>\n";
 }
 $sqldr.="</table></div>\n".$abtn;
}
function print_header(){
 global $err_msg,$VERSION,$DB,$dbh,$self,$is_sht,$xurl,$SHOW_T;
 $dbn=$DB['db'];
?>
<!DOCTYPE html>
<html>
<head><title>phpMiniAdmin</title>
<meta charset="utf-8">
<style type="text/css">
*{box-sizing:border-box;}
body{font-family:Arial,sans-serif;font-size:80%;padding:0;margin:0}
div{padding:3px}
pre{font-size:125%}
textarea{width:100%}
.nav{text-align:center}
.ft{text-align:right;margin-top:20px;font-size:smaller}
.inv{background-color:#069;color:#FFF}
.inv a{color:#FFF}
table{border-collapse:collapse}
table.res{width:100%}
table.wa{width:auto}
table.res th,table.res td{padding:2px;border:1px solid #fff;vertical-align:top}
table.sm th,table.sm td{max-width:30em}
table.sm th>div,table.sm td>div{max-height:3.5em;overflow:hidden}
table.sm th.lg,table.sm td.lg{max-width:inherit}
table.sm th.lg>div,table.sm td.lg>div{max-height:inherit;overflow:inherit}
table.restr{vertical-align:top}
tr.e{background-color:#CCC}
tr.o{background-color:#EEE}
tr.e:hover, tr.o:hover{background-color:#FF9}
tr.h{background-color:#99C}
tr.s{background-color:#FF9}
.err{color:#F33;font-weight:bold;text-align:center}
.frm{width:450px;border:1px solid #999;background-color:#eee;text-align:left}
.frm label .l{width:100px;float:left}
.dot{border-bottom:1px dotted #000}
.ajax{text-decoration:none;border-bottom: 1px dashed}
.qnav{width:30px}
.sbtn{width:100px}
.clear{clear:both;height:0;display:block}
.pi a{text-decoration:none}
.pi hr{display:none}
.pi img{float:right}
.pi .center{text-align:center}
.pi table{margin:0 auto}
.pi table td, .pi table th{border:1px solid #000000;text-align:left;vertical-align:baseline}
.pi table .e{background-color:#ccccff;font-weight:bold}
.pi table .v{background-color:#cccccc}
</style>

<script type="text/javascript">
var LSK='pma_',LSKX=LSK+'max',LSKM=LSK+'min',qcur=0,LSMAX=32;
function $(i){return document.getElementById(i)}
function frefresh(){
 var F=document.DF;
 F.method='get';
 F.refresh.value="1";
 F.GoSQL.click();
}
function go(p,sql){
 var F=document.DF;
 F.p.value=p;
 if(sql)F.q.value=sql;
 F.GoSQL.click();
}
function ays(){
 return confirm('Are you sure to continue?');
}
function chksql(){
 var F=document.DF,v=F.qraw.value;
 if(/^\s*(?:delete|drop|truncate|alter)/.test(v)) if(!ays())return false;
 if(lschk(1)){
  var lsm=lsmax()+1,ls=localStorage;
  ls[LSK+lsm]=v;
  ls[LSKX]=lsm;
  //keep just last LSMAX queries in log
  if(!ls[LSKM])ls[LSKM]=1;
  var lsmin=parseInt(ls[LSKM]);
  if((lsm-lsmin+1)>LSMAX){
   lsclean(lsmin,lsm-LSMAX);
  }
 }
 return true;
}
function tc(tr){
 if (tr.className=='s'){
  tr.className=tr.classNameX;
 }else{
  tr.classNameX=tr.className;
  tr.className='s';
 }
}
function lschk(skip){
 if (!localStorage || !skip && !localStorage[LSKX]) return false;
 return true;
}
function lsmax(){
 var ls=localStorage;
 if(!lschk() || !ls[LSKX])return 0;
 return parseInt(ls[LSKX]);
}
function lsclean(from,to){
 ls=localStorage;
 for(var i=from;i<=to;i++){
  delete ls[LSK+i];ls[LSKM]=i+1;
 }
}
function q_prev(){
 var ls=localStorage;
 if(!lschk())return;
 qcur--;
 var x=parseInt(ls[LSKM]);
 if(qcur<x)qcur=x;
 $('qraw').value=ls[LSK+qcur];
}
function q_next(){
 var ls=localStorage;
 if(!lschk())return;
 qcur++;
 var x=parseInt(ls[LSKX]);
 if(qcur>x)qcur=x;
 $('qraw').value=ls[LSK+qcur];
}
function after_load(){
 var F=document.DF;
 var p=F['v[pwd]'];
 if (p) p.focus();
 qcur=lsmax();
 F.addEventListener('submit',function(e){
  if(!F.qraw)return;
  if(!chksql()){e.preventDefault();return}
  $('q').value=btoa(encodeURIComponent($('qraw').value).replace(/%([0-9A-F]{2})/g,function(m,p){return String.fromCharCode('0x'+p)}));
 });
 var res=$('res');
 if(res)res.addEventListener('dblclick',function(e){
  if(!$('is_sm').checked)return;
  var el=e.target;
  if(el.tagName!='TD')el=el.parentNode;
  if(el.tagName!='TD')return;
  if(el.className.match(/\b\lg\b/))el.className=el.className.replace(/\blg\b/,' ');
  else el.className+=' lg';
 });
}
function logoff(){
 if(lschk()){
  var ls=localStorage;
  var from=parseInt(ls[LSKM]),to=parseInt(ls[LSKX]);
  for(var i=from;i<=to;i++){
   delete ls[LSK+i];
  }
  delete ls[LSKM];delete ls[LSKX];
 }
}
function cfg_toggle(){
 var e=$('cfg-adv');
 e.style.display=e.style.display=='none'?'':'none';
}
function qtpl(s){
 $('qraw').value=s.replace(/%T/g,'`<?php echo $_REQUEST['t']?b64d($_REQUEST['t']):'tablename'?>`');
}
function smview(){
 if($('is_sm').checked){$('res').className+=' sm'}else{$('res').className = $('res').className.replace(/\bsm\b/,' ')}
}
<?php if($is_sht){?>
function chkall(cab){
 var e=document.DF.elements;
 if (e!=null){
  var cl=e.length;
  for (i=0;i<cl;i++){var m=e[i];if(m.checked!=null && m.type=="checkbox"){m.checked=cab.checked}}
 }
}
function sht(f){
 document.DF.dosht.value=f;
}
<?php }?>
</script>

</head>
<body onload="after_load()">
<form method="post" name="DF" id="DF" action="<?php eo($self)?>" enctype="multipart/form-data">
<input type="hidden" name="XSS" value="<?php eo($_SESSION['XSS'])?>">
<input type="hidden" name="refresh" value="">
<input type="hidden" name="p" value="">

<div class="inv">
<a href="http://phpminiadmin.sourceforge.net/" target="_blank"><b>phpMiniAdmin <?php eo($VERSION)?></b></a>
<?php if ($_SESSION['is_logged'] && $dbh){ ?>
 | <a href="?<?php eo($xurl.'&q='.b64u("show databases"))?>">Databases</a>: <select name="db" onChange="frefresh()"><option value='*'> - select/refresh -</option><option value=''> - show all -</option>
<?php echo get_db_select($dbn)?></select>
<?php if($dbn){ $z=" &#183; <a href='".hs($self."?$xurl&db=".ue($dbn)); ?>
<?php echo $z.'&q='.b64u($SHOW_T)?>'>show tables</a>
<?php echo $z?>&shex=1'>export</a>
<?php echo $z?>&shim=1'>import</a>
<?php } ?>
 | <a href="?showcfg=1">Settings</a>
<?php } ?>
<?php if ($_SESSION['is_logged']){?> | <a href="?<?php eo($xurl)?>&logoff=1" onclick="logoff()">Logoff</a> <?php }?>
 | <a href="?pi=1">phpinfo</a>
</div>

<div class="err"><?php eo($err_msg)?></div>

<?php
}
function print_screen(){
 global $out_message, $SQLq, $err_msg, $reccount, $time_all, $sqldr, $page, $MAX_ROWS_PER_PAGE, $is_limited_sql, $last_count, $is_sm;
 $nav='';
 if ($is_limited_sql && ($page || $reccount>=$MAX_ROWS_PER_PAGE) ){
  $nav="<div class='nav'>".get_nav($page, 10000, $MAX_ROWS_PER_PAGE, "javascript:go(%p%)")."</div>";
 }
 print_header();
?>

<div class="dot" style="padding:3px 20px">
<label for="qraw">SQL-query (or multiple queries separated by ";"):</label>&nbsp;<button type="button" class="qnav" onclick="q_prev()">&lt;</button><button type="button" class="qnav" onclick="q_next()">&gt;</button><br>
<textarea id="qraw" cols="70" rows="10"><?php eo($SQLq)?></textarea><br>
<input type="hidden" name="q" id="q" value="<?php b64e($SQLq);?>">
<input type="submit" name="GoSQL" value="Go" class="sbtn">
<input type="button" name="Clear" value=" Clear " onclick="$('qraw').value='';" style="width:100px">
<?php if(!empty($_REQUEST['db'])){ ?>
<div style="float:right">
<input type="button" value="Select" class="sbtn" onclick="qtpl('SELECT *\nFROM %T\nWHERE 1')">
<input type="button" value="Insert" class="sbtn" onclick="qtpl('INSERT INTO %T (`column`, `column`)\nVALUES (\'value\', \'value\')')">
<input type="button" value="Update" class="sbtn" onclick="qtpl('UPDATE %T\nSET `column`=\'value\'\nWHERE 1=0')">
<input type="button" value="Delete" class="sbtn" onclick="qtpl('DELETE FROM %T\nWHERE 1=0')">
</div><br class="clear">
<?php } ?>
</div>
<div class="dot">
<div style="float:right;padding:0 15px"><label><input type="checkbox" name="is_sm" value="1" id="is_sm" onclick="smview()" <?php eo($is_sm?'checked':'')?>> compact view</label></div>
Records: <b><?php eo($reccount); if(!is_null($last_count) && $reccount<$last_count){eo(' out of '.$last_count);}?></b> in <b><?php eo($time_all)?></b> sec<br>
<b><?php eo($out_message)?></b>
</div>
<?php echo $nav.$sqldr.$nav; ?>
<?php
 print_footer();
}
function print_footer(){
?>
</form>
<div class="ft">&copy; 2004-2017 <a href="http://osalabs.com" target="_blank">Oleg Savchuk</a></div>
</body></html>
<?php
}
function print_login(){
 print_header();
?>
<center>
<h3>Access protected by password</h3>
<div style="width:400px;border:1px solid #999999;background-color:#eeeeee">
<label>Password: <input type="password" name="pwd" value=""></label>
<input type="hidden" name="login" value="1">
<input type="submit" value=" Login ">
</div>
</center>
<?php
 print_footer();
}
function print_cfg(){
 global $DB,$err_msg,$self;
 print_header();
?>
<center>
<h3>DB Connection Settings</h3>
<div class="frm">
<label><div class="l">DB user name:</div><input type="text" name="v[user]" value="<?php eo($DB['user'])?>"></label><br>
<label><div class="l">Password:</div><input type="password" name="v[pwd]" value=""></label><br>
<div style="text-align:right"><a href="#" class="ajax" onclick="cfg_toggle()">advanced settings</a></div>
<div id="cfg-adv" style="display:none;">
<label><div class="l">DB name:</div><input type="text" name="v[db]" value="<?php eo($DB['db'])?>"></label><br>
<label><div class="l">MySQL host:</div><input type="text" name="v[host]" value="<?php eo($DB['host'])?>"></label> <label>port: <input type="text" name="v[port]" value="<?php eo($DB['port'])?>" size="4"></label> <label>socket: <input type="text" name="v[socket]" value="<?php eo($DB['socket'])?>" size="4"></label><br>
<label><div class="l">Charset:</div><select name="v[chset]"><option value="">- default -&.........完整代码请登录后点击上方下载按钮下载查看

网友评论0