Skip to content

Instantly share code, notes, and snippets.

@dominikwilkowski
Created February 25, 2014 23:01
Show Gist options
  • Save dominikwilkowski/9219847 to your computer and use it in GitHub Desktop.
Save dominikwilkowski/9219847 to your computer and use it in GitHub Desktop.
Run Adminer with custom Session class (in database rather than file system)
<?php
include('php/ini.php'); //get mySQL settings
$SESSIONTAB = 'session'; //table for PHP sessions
/*****************************| MYSQLI CONNECTION FUNCTION |*****************************/
/**
* Simple MySQLi abstraction layer
*
* @param resource $mysqli The MySQLi connection link
* @param string $query The MySQL query for prepaired statement
* @param array $v The parameters to replace ? in $query. First element must be the type
* @param integer $o Option for more debug infos [0]=no infos(default) [1]=adding debug infos
*
* @return array [for select]=associative array of table result [for everything else]=associative array with affectedRows,info and insertID
*
* @author Dominik Wilkowski <[email protected]>
* @copyright 2013 Dominik Wilkowski
*/
$connect2DB = function($mysqli, $query, $v=array(), $o=0) {
if($mysqli -> connect_errno) {
return array('info'=>array('error'=>'Connect failed: '.$mysqli->connect_error)); //error handling here
exit();
}
if($v && (substr_count($query,"?")!=strlen($v[0]) || strlen($v[0])!=((count($v)-1)>=0 ? (count($v)-1) : 0))) {
return array('info'=>array('error'=>'Placeholders are unequal! placeholders:'.substr_count($query,"?").', replacements:'.strlen($v[0]).', param:'.(count($v)-1).' ('.$v[0].')')); //error handling here...
exit();
}
if($res = $mysqli->prepare($query)) {
//dynamically bind all $v
if($v) {
$values=array($v[0]);
for($i=1; $i<count($v); $i++) {
${'bind'.$i}=$v[$i];
$values[]=&${'bind'.$i};
}
call_user_func_array(array($res,'bind_param'),$values);
}
$res -> execute();
//bind all table rows to result
if(strtolower(substr($query,0,6))=="select") {
$field=$fields=$tempRow=array();
$meta=$res->result_metadata();
while($field=$meta->fetch_field()) {
$fieldName=$field->name;
$fields[]=&$tempRow[$fieldName];
}
$meta -> free_result();
call_user_func_array(array($res,"bind_result"),$fields);
//return associative array
$results=array();
$i=0;
while($res->fetch()) {
$results["res"][$i]=array();
foreach($tempRow as $k=>$v2) $results["res"][$i][$k] = $v2;
$i++;
}
$res->free_result();
}
else { //return infos about the query
if($mysqli->warning_count) {
if($err=$mysqli->query("SHOW WARNINGS")) {
$row=$err->fetch_row();
$results["info"]["error"].=$row[0].' ('.$row[1].'): '.$row[2];
$err->close();
}
}
$results["info"]["affectedRows"]=$mysqli->affected_rows;
$results["info"]["info"]=$mysqli->info;
$results["info"]["insertID"]=$mysqli->insert_id;
}
$res->close();
}
if($o===1) { //adding debug infos
$q=$query;
for($i=1;$i<count($v);$i++) $q=preg_replace("/\?/",(substr($v[0],($i-1),1)=="s" ? '"' : '').$v[$i].(substr($v[0],($i-1),1)=="s" ? '"' : ''),$q,1);
$results["info"]["query"]=$q;
$results["info"]["param"]=json_encode($v);
}
if(strtolower(substr($query,0,6))=="update" || strtolower(substr($query,0,6))=="delete") { //optimize at update and delete
preg_match_all('/((update|delete) `(.*)` )/i',$query,$tables);
foreach($tables[3] as $t) $mysqli->query('OPTIMIZE TABLE '.$t);
}
return $results;
};
/**
* SESSION HANDLER CLASS
*
* @author Dominik Wilkowski
*/
class sessionDBHandler {
public function __construct() {
session_set_save_handler(
array($this, "_open"),
array($this, "_close"),
array($this, "_read"),
array($this, "_write"),
array($this, "_destroy"),
array($this, "_gc")
);
register_shutdown_function('session_write_close');
}
/**
* open mysql connection
*/
public function _open() {
global $sessCon;
$sessCon=new mysqli(HOST,USER,PW,DATABASE); //mysqli connection
}
/**
* close mysql connection
*/
public function _close() {
global $sessCon;
$sessCon->close();
}
/**
* read session data
*
* @param string $id Session ID
*
* @return string Session data saved in DB
*/
public function _read($id) {
global $sessCon;
global $connect2DB;
global $SESSIONTAB;
$qRes=$connect2DB($sessCon,'select `data` from `'.$SESSIONTAB.'` where `ID`=?',array("s",$id));
if(!empty($qRes["res"][0]["data"])) return $qRes["res"][0]["data"];
else return '';
}
/**
* write session data
*
* @param string $id Session ID
* @param string $data Session Data
*
* @return bool
*/
public function _write($id,$data) {
global $sessCon;
global $connect2DB;
global $SESSIONTAB;
$qRes=$connect2DB($sessCon,'select `ID` from `'.$SESSIONTAB.'` where `ID`=?',array("s",$id));
$param=array(); //buliding SQL query parameters
$param[0]="sis";
$param[]=$id;
$param[]=time();
$param[]=$data;
if(!empty($qRes["res"][0]["ID"])) {
$param[0].="s";
$param[]=$id;
}
$qRes=$connect2DB($sessCon,(!empty($qRes["res"][0]["ID"]) ? 'update' : 'insert').' `'.$SESSIONTAB.'` set `ID`=?, `access`=?, `data`=?'.(!empty($qRes["res"][0]["ID"]) ? ' where `ID`=?' : ''),$param);
if($qRes["info"]["affectedRows"]>0) return true;
else return false;
}
/**
* destroty session
*
* @param string $id Session ID
*
* @return bool
*/
public function _destroy($id) {
global $sessCon;
global $connect2DB;
global $SESSIONTAB;
$qRes=$connect2DB($sessCon,'delete from `'.$SESSIONTAB.'` where `ID`=?',array("s",$id));
if($qRes["info"]["affectedRows"]>0) return true;
else return '';
}
/**
* clean sessions
*
* @param int $max Session life time
*
* @return bool
*/
public function _gc($max) {
global $sessCon;
global $connect2DB;
global $SESSIONTAB;
$qRes=$connect2DB($sessCon,'delete from `'.$SESSIONTAB.'` where `access`<?',array("i",(time()-$max)));
if($qRes["info"]["affectedRows"]>0) return true;
else return false;
}
}
new sessionDBHandler(); //save sessions into the database
session_start(); //login session
include "adminer.php";
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment