- 浏览: 27188 次
- 性别:
- 来自: 苏州
文章分类
最新评论
收藏列表
标题 | 标签 | 来源 | |
linux 系统修复 | |||
输入root密码 #mount | grep "on /" //得到root用户所在分区/dev/your_partition #fsck -y /dev/root #fsck -y /dev/your_partition #fsck -y /dev/sda1 //检测并修复磁盘/dev/root,-y 选项指定检测每个文件是自动输入yes #chown root.root /var/log/audit/audit.log #chmod 600 /var/log/audit/audit.log //给root写auditd日志文件的权限 #reboot //重启系统,成功进入系统 |
|||
80端口被NT kernel & System 占用pid 4 | |||
前段时间停止了Apache,结果在打开的时候发现无法打开,80端口被占用,于是win+r 运行cmd 输入netstat -ano 加载中... 可以看到80端口被PID4占用,于是打开任务管理器-进程-查看,选择列,勾选PID 可以看到pid 4 的被NT kernel & System 占用 加载中... 在网上找了很久找到解决方案 http://www.cameroncooke.com/2009/01/25/windows-7-uses-port-80-and-makes-it-impossible-to-install-apache-solution/comment-page-1/#comments 原文: 翻译如下: 该进程是Http.sys。它是http API的驱动组件,Http栈服务器。如果该端口被Http.sys占用,说明一些正在使用http.sys的应用程序在运行。这就是阻止Apache运行的原因,因为Http.sys占用着80端口。我们提供了一种应用程序的机制来帮助控制端口共享,但是我需要调查导致你遇到这种困难的是什么特殊应用程序。如果你能提供给我们“netsh http show servicestate”这条命令的输出结果,我就能找出是哪个应用程序在使用Http.sys。在你禁用Http.sys之前,请按照下面的步骤来运行命令: 1. sc config http stat = demand 2. reboot 3. run the command(netsh http show servicestat)as administrator 在你使用这个命令之前,你可以按照下面步骤禁用http.sys: 1. net stop http 2. Sc config http start= disabled 于是运行net stop http 加载中... 按y 确定 加载中... 在运行 Sc config http start= disabled 加载中... 好了,现在启动Apache,可以启动了。 在查看一下netstat -ano 发现pid 4占用了445端口 |
|||
百度天气api | 接口 | ||
百度天气:http://api.map.baidu.com/telematics/v3/weather?location=%E5%8C%97%E4%BA%AC&output=json&ak=5slgyqGDENN7Sy7pw29IUvrZ |
|||
Mysql导出表结构及表数据 mysqldump用法 | |||
命令行下具体用法如下: mysqldump -u用戶名 -p密码 -d 数据库库名 表名 脚本名; 1、导出数据库为dbname的表结构(其中用戶名为root,密码为dbpasswd,生成的脚本名为db.sql) mysqldump -uroot -pdbpasswd -d dbname >db.sql; 2、导出数据库库为dbname某张表为(test)结构 mysqldump -uroot -pdbpasswd -d dbname test>db.sql; 3、导出数据库库为dbname所有表结构及表数据库(不加-d) mysqldump -uroot -pdbpasswd dbname >db.sql; 4、导出数据库库为dbname某张表为(test)结构及表数据库(不加-d) mysqldump -uroot -pdbpasswd dbname test>db.sql; 5、导出数据库库为dbname某张表为(test)数据 mysqldump -uroot -pdbpasswd dbname test>db.sql; 6、指定条件导出数据库为dbname某张表为(test)数据(加-w) mysqldump -uroot -pdbpasswd dbname test -w " 条件可带变量 ">db.sql; |
|||
php原生soap | php | ||
server.php <?php /* * soap 服务 * 采用nusoap类库 1.2 * utf8编码 hkey 是简单的数据校验 */ header("Content-type: text/html; charset=utf-8");//最好声明一下编码 @set_time_limit(600); $hkey = 'sdfsdfsd34345dfdg56sdfsdf';//密钥,简单的校验。。更加复杂的算法。。可以另外实现 function test($mask,$val) { global $hkey; $_mask = base64_decode($mask); if ($hkey != $_mask) { return 403; } return $val; } $soap = new SoapServer(null, array('uri' => "")); $soap->addFunction('test');//注册单个方法 //$soap->addFunction(SOAP_FUNCTIONS_ALL);//可以一次过全部注册 $soap->handle(); ?> client.php <?php $key = base64_decode('sdfsdfsd34345dfdg56sdfsdf'); $url = "http://localhost/server.php"; try { $client = new SoapClient(null, array('location' => $url, 'uri' => "http://test-uri/")); $reversed = $client->test($key,500); print_r($reversed); } catch (SoapFault $fault) { echo "Fault! code:", $fault->faultcode, ", string: ", $fault->faultstring; } ?> |
|||
alexa api 请求 | php | ||
<?php /** * @File name: ParseXml.class.php * @todo: parsing XML(string or file or url) * @author: zhys9 @ 2008-03-24 <email>hide@address.com</email> * example: * <code> * $xml = new ParseXml(); * $xml->LoadFile("test.xml"); * //$xml->LoadString($xmlString); * //$xml->LoadRemote("http"//www.yourdomain.com/dir/filename.xml", 3); * $dataArray = $xml->ToArray(); * print_r($dataArray); * </code> */ class ParseXml { var $xmlStr; var $xmlFile; var $obj; var $aArray; var $timeOut; var $charsetOutput; function ParseXml() { } /** * @param String xmlString xml string to parsing */ function LoadString($xmlString) { $this->xmlStr = $xmlString; } /** * @param String Path and file name which you want to parsing, * Also, if fopen wrappers is activated, you can fetch a remote document, but timeout not be supported. */ function LoadFile($file) { $this->xmlFile = $file; $this->xmlStr = @file_get_contents($file); } /** * @todo Load remote xml document * @param string $url URL of xml document. * @param int $timeout timeout default:5s */ function LoadRemote($url, $timeout = 5) { $this->xmlFile = $url; $p = parse_url($url); if ($p['scheme'] == 'http') { $host = $p['host']; $pos = $p['path']; $pos .= isset($p['query']) ? sprintf("?%s", $p['query']) : ''; $port = isset($p['port']) ? $p['port'] : 80; $this->xmlStr = $this->Async_file_get_contents($host, $pos, $port, $timeout); } else { return false; } } /** * @todo Set attributes. * @param array $set array('attribute_name'=>'value') */ function Set(array $set) { foreach ($set as $attribute => $value) { if ($attribute == 'charsetOutput') { $value = strtoupper($value); } $this->$attribute = $value; } } /** * @todo Convert charset,if you want to output data with a charset not "UTF-8", * this member function must be useful. * @param string $string 需转换的字符串 */ function ConvertCharset($string) { if ('UTF-8' != $this->charsetOutput) { if (function_exists("iconv")) { $string = iconv('UTF-8', $this->charsetOutput, $string); } elseif (function_exists("mb_convert_encoding")) { $string = mb_convert_encoding($string, $this->charsetOutput, 'UTF-8'); } else { die('Function "iconv" or "mb_convert_encoding" needed!'); } } return $string; } /** * 解析xml */ function Parse() { $this->obj = simplexml_load_string($this->xmlStr); } /** * @return Array Result of parsing. */ function ToArray() { if (empty($this->obj)) { $this->Parse(); } $this->aArray = $this->Object2array($this->obj); return $this->aArray; } /** * @param Object object Objects you want convert to array. * @return Array */ function Object2array($object) { $return = array(); if (is_array($object)) { foreach ($object as $key => $value) { $return[$key] = $this->Object2array($value); } } else { $var = get_object_vars($object); if ($var) { foreach ($var as $key => $value) { $return[$key] = ($key && ($value == null)) ? null : $this->Object2array($value); } } else { return $this->ConvertCharset((string) $object); } } return $return; } /** * @todo Fetch a remote document with HTTP protect. * @param string $site Server's IP/Domain * @param string $pos URI to be requested * @param int $port Port default:80 * @param int $timeout Timeout default:5s * @return string/false Data or FALSE when timeout. */ function Async_file_get_contents($site, $pos, $port = 80, $timeout = 5) { $fp = fsockopen($site, $port, $errno, $errstr, 5); if (!$fp) { return false; } else { fwrite($fp, "GET $pos HTTP/1.0\r\n"); fwrite($fp, "Host: $site\r\n\r\n"); stream_set_timeout($fp, $timeout); $res = stream_get_contents($fp); $info = stream_get_meta_data($fp); fclose($fp); if ($info['timed_out']) { return false; } else { return substr(strstr($res, "\r\n\r\n"), 4); } } } /** * @todo Get xmlStr of current object. * @return string xmlStr */ function GetXmlStr() { return $this->xmlStr; } } class AlexaRank extends ParseXml { private $data; private $values = array(); function __construct($domain) { $this->data = $this->fetchData($domain); $this->findValue(); } private function fetchData($domain) { $url = "http://data.alexa.com/data?cli=10&dat=snbamz&url=http://" . trim($domain); $this->LoadRemote($url, 5); $dataArray = $this->ToArray(); return $dataArray; } private function findValue() { $this->values = array( '世界排名' => (isset($this->data['SD'][1]['POPULARITY']['@attributes']['TEXT']) ? ($this->data['SD'][1]['POPULARITY']['@attributes']['TEXT']) : NULL), '中国排名' => (isset($this->data['SD'][1]['COUNTRY']['@attributes']['RANK']) ? ($this->data['SD'][1]['COUNTRY']['@attributes']['RANK']) : NULL), '三月排名变化' => (isset($this->data['SD'][1]['RANK']['@attributes']['DELTA']) ? ($this->data['SD'][1]['RANK']['@attributes']['DELTA']) : NULL), // 'created' => (isset($this->data['SD'][0]['CREATED']['@attributes']['DATE']) ? ($this->data['SD'][0]['CREATED']['@attributes']['DATE']) : NULL), // 'email' => (isset($this->data['SD'][0]['EMAIL']['@attributes']['ADDR']) ? ($this->data['SD'][0]['EMAIL']['@attributes']['ADDR']) : NULL), '反向链接' => (isset($this->data['SD'][0]['LINKSIN']['@attributes']['NUM']) ? ($this->data['SD'][0]['LINKSIN']['@attributes']['NUM']) : NULL), 'reach' => (isset($this->data['SD'][1]['REACH']['@attributes']['RANK']) ? ($this->data['SD'][1]['REACH']['@attributes']['RANK']) : NULL), // 'baseuri' => (isset($this->data['DMOZ']['SITE']['@attributes']['BASE']) ? ($this->data['DMOZ']['SITE']['@attributes']['BASE']) : NULL), // 'title' => (isset($this->data['DMOZ']['SITE']['@attributes']['TITLE']) ? ($this->data['DMOZ']['SITE']['@attributes']['TITLE']) : NULL), // 'description' => (isset($this->data['DMOZ']['SITE']['@attributes']['DESC']) ? ($this->data['DMOZ']['SITE']['@attributes']['DESC']) : NULL), ); } public function get($value = NULL) { if ($value === NULL) { return $this->values; //Return the total Array } else { return (isset($this->values[$value]) ? $this->values[$value] : '"' . $value . '" does not exist.'); } } } error_reporting(0); header("Content-type: text/html; charset=utf-8"); $sitelist = array("gzmama.com", 'mama.cn', 'bjmama.com', 'tjmama.com','cdmama.cn'); foreach ($sitelist as $site) { $url = new AlexaRank($site); $alexa = $url->get(); echo $site; print_r($alexa); echo "<br>"; } ?> |
|||
cvs数据导入mysql | php | ||
$sql = <<<EOF DROP TABLE IF EXISTS `pre_ty_hui_list`; EOF; //DB::query($sql); $sql = <<<EOF CREATE TABLE IF NOT EXISTS `pre_ty_hui_list` ( `hid` mediumint(8) NOT NULL auto_increment, `hcode` varchar(50) NOT NULL, `htype` tinyint(2) NOT NULL default '0', `hpwd` varchar(50) NOT NULL, `hsubject` varchar(80) NOT NULL, `hdesc` varchar(200) NOT NULL, `hday` int(10) NOT NULL, `adminid` mediumint(8) NOT NULL, `postip` char(15) NOT NULL, `posttime` int(10) NOT NULL, `ouid` mediumint(8) NOT NULL, `ousername` char(15) NOT NULL, `otime` int(10) NOT NULL, `oip` char(15) NOT NULL, PRIMARY KEY (`hid`), UNIQUE KEY `hcode` (`hcode`), KEY `ouid` (`ouid`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=9241 ; EOF; //DB::query($sql); //runquery($sql); //exit; $tb = DB::table('ty_hui_list'); $t = $_G['timestamp']; $clientip = $_G['clientip']; $harr = array('500' => 0, '100' => 1,'50'=>2); DB::delete("ty_hui_list"); //清空表,重来 foreach ($harr as $key => $val) { $sql = "INSERT INTO $tb (htype,hcode,hpwd,hsubject,hdesc,adminid,posttime,postip) VALUES ('"; $handle = fopen("$key.csv", "r"); while ($data = fgetcsv($handle, 1000, ",")) { $sql = $sql . $val . "','"; $num = count($data); for ($c = 1; $c < $num; $c++) { // if ($c == 1) { // $data[$c] = $val.$data[$c]; // } if ($c > 2 && $c < 5) { // $data[$c] = base64_encode($data[$c]); $data[$c] = mb_convert_encoding($data[$c], "UTF-8", "GB2312"); } if ($c == $num - 1) { $sql = $sql . $data[$c] . "',"; //表格需要转换编码 表格默认了gb2312 break; } $sql = $sql . $data[$c] . "','"; } $sql = $sql . "1,$t,'$clientip')"; DB::query($sql); print "<br>"; echo $sql . ";<br>"; // $db->query($sql); // // echo "SQL语句执行成功!<br>"; $sql = "INSERT INTO $tb (htype,hcode,hpwd,hsubject,hdesc,adminid,posttime,postip) VALUES ('"; } fclose($handle); } |
|||
php sha1,md5 等与java sha1 md5的兼容性 | php | ||
//很多时候,sha1的值并不相等,也许要用到 mhash但这不是默认的拓展,需要手动安装或加载,这个时候需要注意 pack("H*", md5($str)) == mhash(MHASH_MD5, $str) pack("H*", sha1($str)) == mhash(MHASH_SHA1, $str) |
|||
javascript 实现 php mhash sha1 编码返回 | web前端 | ||
/* * A JavaScript implementation of the Secure Hash Algorithm, SHA-1, as defined * in FIPS 180-1 * Version 2.2 Copyright Paul Johnston 2000 - 2009. * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet * Distributed under the BSD License * See http://pajhome.org.uk/crypt/md5 for details. */ /* * Configurable variables. You may need to tweak these to be compatible with * the server-side, but the defaults work in most cases. */ var hexcase = 0; /* hex output format. 0 - lowercase; 1 - uppercase */ var b64pad = ""; /* base-64 pad character. "=" for strict RFC compliance */ /* * These are the functions you'll usually want to call * They take string arguments and return either hex or base-64 encoded strings */ function hex_sha1(s) { return rstr2hex(rstr_sha1(str2rstr_utf8(s))); } function b64_sha1(s) { return rstr2b64(rstr_sha1(str2rstr_utf8(s))); } function any_sha1(s, e) { return rstr2any(rstr_sha1(str2rstr_utf8(s)), e); } function hex_hmac_sha1(k, d) { return rstr2hex(rstr_hmac_sha1(str2rstr_utf8(k), str2rstr_utf8(d))); } function b64_hmac_sha1(k, d) { return rstr2b64(rstr_hmac_sha1(str2rstr_utf8(k), str2rstr_utf8(d))); } function any_hmac_sha1(k, d, e) { return rstr2any(rstr_hmac_sha1(str2rstr_utf8(k), str2rstr_utf8(d)), e); } /* * Perform a simple self-test to see if the VM is working */ function sha1_vm_test() { return hex_sha1("abc").toLowerCase() == "a9993e364706816aba3e25717850c26c9cd0d89d"; } /* * Calculate the SHA1 of a raw string */ function rstr_sha1(s) { return binb2rstr(binb_sha1(rstr2binb(s), s.length * 8)); } /* * Calculate the HMAC-SHA1 of a key and some data (raw strings) */ function rstr_hmac_sha1(key, data) { var bkey = rstr2binb(key); if(bkey.length > 16) bkey = binb_sha1(bkey, key.length * 8); var ipad = Array(16), opad = Array(16); for(var i = 0; i < 16; i++) {cd44bf3750501c57fa3b57729711adee67d9c0 ipad[i] = bkey[i] ^ 0x36363636; opad[i] = bkey[i] ^ 0x5C5C5C5C; } var hash = binb_sha1(ipad.concat(rstr2binb(data)), 512 + data.length * 8); return binb2rstr(binb_sha1(opad.concat(hash), 512 + 160)); } /* * Convert a raw string to a hex string */ function rstr2hex(input) { try { hexcase } catch(e) { hexcase=0; } var hex_tab = hexcase ? "0123456789ABCDEF" : "0123456789abcdef"; var output = ""; var x; for(var i = 0; i < input.length; i++) { x = input.charCodeAt(i); output += hex_tab.charAt((x >>> 4) & 0x0F) + hex_tab.charAt( x & 0x0F); } return output; } /* * Convert a raw string to a base-64 string */ function rstr2b64(input) { try { b64pad } catch(e) { b64pad=''; } var tab = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; var output = ""; var len = input.length; for(var i = 0; i < len; i += 3) { var triplet = (input.charCodeAt(i) << 16) | (i + 1 < len ? input.charCodeAt(i+1) << 8 : 0) | (i + 2 < len ? input.charCodeAt(i+2) : 0); for(var j = 0; j < 4; j++) { if(i * 8 + j * 6 > input.length * 8) output += b64pad; else output += tab.charAt((triplet >>> 6*(3-j)) & 0x3F); } } return output; } /* * Convert a raw string to an arbitrary string encoding */ function rstr2any(input, encoding) { var divisor = encoding.length; var remainders = Array(); var i, q, x, quotient; /* Convert to an array of 16-bit big-endian values, forming the dividend */ var dividend = Array(Math.ceil(input.length / 2)); for(i = 0; i < dividend.length; i++) { dividend[i] = (input.charCodeAt(i * 2) << 8) | input.charCodeAt(i * 2 + 1); } /* * Repeatedly perform a long division. The binary array forms the dividend, * the length of the encoding is the divisor. Once computed, the quotient * forms the dividend for the next step. We stop when the dividend is zero. * All remainders are stored for later use. */ while(dividend.length > 0) { quotient = Array(); x = 0; for(i = 0; i < dividend.length; i++) { x = (x << 16) + dividend[i]; q = Math.floor(x / divisor); x -= q * divisor; if(quotient.length > 0 || q > 0) quotient[quotient.length] = q; } remainders[remainders.length] = x; dividend = quotient; } /* Convert the remainders to the output string */ var output = ""; for(i = remainders.length - 1; i >= 0; i--) output += encoding.charAt(remainders[i]); /* Append leading zero equivalents */ var full_length = Math.ceil(input.length * 8 / (Math.log(encoding.length) / Math.log(2))) for(i = output.length; i < full_length; i++) output = encoding[0] + output; return output; } /* * Encode a string as utf-8. * For efficiency, this assumes the input is valid utf-16. */ function str2rstr_utf8(input) { var output = ""; var i = -1; var x, y; while(++i < input.length) { /* Decode utf-16 surrogate pairs */ x = input.charCodeAt(i); y = i + 1 < input.length ? input.charCodeAt(i + 1) : 0; if(0xD800 <= x && x <= 0xDBFF && 0xDC00 <= y && y <= 0xDFFF) { x = 0x10000 + ((x & 0x03FF) << 10) + (y & 0x03FF); i++; } /* Encode output as utf-8 */ if(x <= 0x7F) output += String.fromCharCode(x); else if(x <= 0x7FF) output += String.fromCharCode(0xC0 | ((x >>> 6 ) & 0x1F), 0x80 | ( x & 0x3F)); else if(x <= 0xFFFF) output += String.fromCharCode(0xE0 | ((x >>> 12) & 0x0F), 0x80 | ((x >>> 6 ) & 0x3F), 0x80 | ( x & 0x3F)); else if(x <= 0x1FFFFF) output += String.fromCharCode(0xF0 | ((x >>> 18) & 0x07), 0x80 | ((x >>> 12) & 0x3F), 0x80 | ((x >>> 6 ) & 0x3F), 0x80 | ( x & 0x3F)); } return output; } /* * Encode a string as utf-16 */ function str2rstr_utf16le(input) { var output = ""; for(var i = 0; i < input.length; i++) output += String.fromCharCode( input.charCodeAt(i) & 0xFF, (input.charCodeAt(i) >>> 8) & 0xFF); return output; } function str2rstr_utf16be(input) { var output = ""; for(var i = 0; i < input.length; i++) output += String.fromCharCode((input.charCodeAt(i) >>> 8) & 0xFF, input.charCodeAt(i) & 0xFF); return output; } /* * Convert a raw string to an array of big-endian words * Characters >255 have their high-byte silently ignored. */ function rstr2binb(input) { var output = Array(input.length >> 2); for(var i = 0; i < output.length; i++) output[i] = 0; for(var i = 0; i < input.length * 8; i += 8) output[i>>5] |= (input.charCodeAt(i / 8) & 0xFF) << (24 - i % 32); return output; } /* * Convert an array of big-endian words to a string */ function binb2rstr(input) { var output = ""; for(var i = 0; i < input.length * 32; i += 8) output += String.fromCharCode((input[i>>5] >>> (24 - i % 32)) & 0xFF); return output; } /* * Calculate the SHA-1 of an array of big-endian words, and a bit length */ function binb_sha1(x, len) { /* append padding */ x[len >> 5] |= 0x80 << (24 - len % 32); x[((len + 64 >> 9) << 4) + 15] = len; var w = Array(80); var a = 1732584193; var b = -271733879; var c = -1732584194; var d = 271733878; var e = -1009589776; for(var i = 0; i < x.length; i += 16) { var olda = a; var oldb = b; var oldc = c; var oldd = d; var olde = e; for(var j = 0; j < 80; j++) { if(j < 16) w[j] = x[i + j]; else w[j] = bit_rol(w[j-3] ^ w[j-8] ^ w[j-14] ^ w[j-16], 1); var t = safe_add(safe_add(bit_rol(a, 5), sha1_ft(j, b, c, d)), safe_add(safe_add(e, w[j]), sha1_kt(j))); e = d; d = c; c = bit_rol(b, 30); b = a; a = t; } a = safe_add(a, olda); b = safe_add(b, oldb); c = safe_add(c, oldc); d = safe_add(d, oldd); e = safe_add(e, olde); } return Array(a, b, c, d, e); } /* * Perform the appropriate triplet combination function for the current * iteration */ function sha1_ft(t, b, c, d) { if(t < 20) return (b & c) | ((~b) & d); if(t < 40) return b ^ c ^ d; if(t < 60) return (b & c) | (b & d) | (c & d); return b ^ c ^ d; } /* * Determine the appropriate additive constant for the current iteration */ function sha1_kt(t) { return (t < 20) ? 1518500249 : (t < 40) ? 1859775393 : (t < 60) ? -1894007588 : -899497514; } /* * Add integers, wrapping at 2^32. This uses 16-bit operations internally * to work around bugs in some JS interpreters. */ function safe_add(x, y) { var lsw = (x & 0xFFFF) + (y & 0xFFFF); var msw = (x >> 16) + (y >> 16) + (lsw >> 16); return (msw << 16) | (lsw & 0xFFFF); } /* * Bitwise rotate a 32-bit number to the left. */ function bit_rol(num, cnt) { return (num << cnt) | (num >>> (32 - cnt)); } |
|||
中国电信UDB 3DES 加密解密算法 PHP版 | php | ||
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>中国电信会员单点鉴权接口</title> </head> <body> <?php //header("Content-Type: text/html; charset=utf-8"); error_reporting(E_ALL); error_reporting(E_CORE_ERROR); /** * 中国电信用户鉴权接口 PHP版本 v201202 * @UDB设备号:由中国电信系统发放 * @业务系统设备号:由中国电信系统发放 * @密钥:由中国电信系统发放 直接使用pack("H48",key)进行转换即可,警告可以不理会 * @向量:由中国电信系统发放 //需要补零成16位后(即0102030405060708) 进行pack("H16",iv) * @hash sha1 必须使用 mhash(MHASH_SHA1,"明文") 不要使用直接使用sha1 * 如果的系统不支持mhash,那么请用pack("H*",sha1($str))取代 * @abstract 3des cbc PKCS7Padding */ class PHP3DES { private $SysKey = ' key values'; private $iv = ' iv values'; /** * 加密 CBC */ public function encrypt($value) { $td = mcrypt_module_open(MCRYPT_3DES, '', MCRYPT_MODE_CBC, ''); $key = pack('H48', $this->SysKey); $iv = pack('H16', $this->iv); $value = $this->PaddingPKCS7($value); //填充 mcrypt_generic_init($td, $key, $iv); $ret = mcrypt_generic($td, $value); mcrypt_generic_deinit($td); mcrypt_module_close($td); return $ret; } /** * 解密 */ public function decrypt($value) { $td = mcrypt_module_open(MCRYPT_3DES, '', MCRYPT_MODE_CBC, ''); $key = pack('H48', $this->SysKey); $iv = pack('H16', $this->iv); mcrypt_generic_init($td, $key, $iv); $ret = mdecrypt_generic($td, $value); $ret = $this->UnPaddingPKCS7($ret); mcrypt_generic_deinit($td); mcrypt_module_close($td); return $ret; } /* * 填充 */ private function PaddingPKCS7($text) { $text_add = strlen($text) % 8; for ($i = $text_add; $i < 8; $i++) { $text .= chr(8 - $text_add); } return $text; } /* * 消除填充 */ private function UnPaddingPKCS7($text) { $pad = ord($text{strlen($text) - 1}); if ($pad > strlen($text)) { return false; } if (strspn($text, chr($pad), strlen($text) - $pad) != $pad) { return false; } return substr($text, 0, -1 * $pad); } } //开始调用 $SrcSsDeviceNo = 'your value'; $Timestamp = date('Y-m-d H:i:s'); $ReturnUrl = 'your url'; $DigestStr = $SrcSsDeviceNo . $Timestamp . $ReturnUrl; $Digest = base64_encode(mhash(MHASH_SHA1, $DigestStr)); //必须使用mhash,sha1的结果不一样 $BaseStr = $Timestamp . '$' . $ReturnUrl . '$' . $Digest; $DoDes = new PHP3DES(); $encrystr = $DoDes->encrypt($BaseStr); //登陆参数 $PassportCheckRequest = $PassportLoginRequest = urlencode($SrcSsDeviceNo . '$' . base64_encode($encrystr)); //通行证登陆接口 $PassportLoginUrl = 'your url'; $PassportLoginUrl .=$PassportLoginRequest; //一键登陆接口 $PassportCheckUrl = 'your url ' . $PassportCheckRequest; if ($_GET['PassportLoginResponse'] || $_GET['PassportCheckResponse']) { print_r("<pre>"); $PassportLoginResponseStr = $_GET['PassportLoginResponse']; if (!$PassportLoginResponseStr) { $PassportLoginResponseStr = $_GET['PassportCheckResponse']; } echo '服务端返回:',$PassportLoginResponseStr; echo "<br>"; $ResponseArr = explode('$', urldecode($PassportLoginResponseStr)); print_r($ResponseArr); $ResponDesStr = str_replace(" ", "+", $ResponseArr[1]); echo "<br><hr>"; $ResponDesStr = $DoDes->decrypt(base64_decode($ResponDesStr)); echo " 解密的:"; echo $ResponDesStr; echo "<br>"; $ResponDesArr = explode('$', $ResponDesStr); print_r($ResponDesArr); $UDBticket = $ResponDesArr[1]; echo "<br>"; echo 'UDBticket:', $UDBticket; echo "<br>"; echo "原digest:", $ResponDesArr[3]; echo "<br>"; echo"现digest:", base64_encode(mhash(MHASH_SHA1, $ResponDesArr[0] . '$' . $ResponseArr[0] . '$' . $UDBticket . '$' . $ResponDesArr[2])); echo "<br><hr>"; //WEBSERVICE获取用户信息 $wsdl_url = "your url"; $client = new SoapClient($wsdl_url); $AuthSsDeviceNo = $SrcSsDeviceNo; $Authenticator = base64_encode($DoDes->encrypt(mhash(MHASH_SHA1, $SrcSsDeviceNo . $AuthSsDeviceNo . $UDBticket . $Timestamp))); // 设置参数(注意:PHP只能以'数组集'方式传递参数,如果服务端是java,用Map接收) $param = array('Authenticator' => $Authenticator, 'SrcSsDeviceNo' => $SrcSsDeviceNo, 'AuthSsDeviceNo' => $AuthSsDeviceNo, 'UDBTicket' => $UDBticket, 'TimeStamp' => $Timestamp, ); try { $result = $client->__soapCall('AccountInfoCheck', array('parameters' => $param)); echo "WebService:AccountInfoCheck 帐号信息返回"; echo "<br>"; $a1 = get_object_vars($result); $AccountInfoArr = get_object_vars($a1['AccountInfoCheckResult']); print_r($AccountInfoArr); } catch (SoapFault $fault) { print_r($fault); //错误输出 } //全局注销接口 $LogoutDigest = base64_encode(mhash(MHASH_SHA1, $SrcSsDeviceNo . $AccountInfoArr[UserID] . $AccountInfoArr[PUserID] . $Timestamp . $ReturnUrl)); $LogoutStr = $SrcSsDeviceNo . '$' . base64_encode($DoDes->encrypt(mhash(MHASH_SHA1, $AccountInfoArr[UserID] . '$' . $AccountInfoArr[PUserID] . '$' . $Timestamp . '$' . $ReturnUrl . '$' . $LogoutDigest))); $PassportLogoutRequest = urlencode($LogoutStr); $PassportLogoutUrl = 'your url' . $PassportLogoutRequest; ?> <div class="login"> <div class="box"> <div class="error" style=" display:none;height:22px;" id="errDemo"> <div class="bg"> <div class="text"><span id="errDes" ></span></div> </div> </div> <?php if (!$AccountInfoArr[UserID]) { ?> <a href="<?= $PassportLoginUrl ?>">通行证登陆</a> <a href="<?= $PassportCheckUrl ?>">一键登陆</a> <form action="<?= $PassportLoginUrl ?>" name="loginForm" method="post"> <input type="hidden" name="returnUrl" value="<?= $ReturnUrl ?>" /> <input type="hidden" name="srcSsDeviceNo" value="<?= $SrcSsDeviceNo ?>" /> <input type="hidden" id="passwordType" name="passwordType" value="00" /> <p> <label>用户名:</label> <input name="account" id="account" type="text" maxlength="15" title="请输入用户名" value="" /> <i>@189.cn</i> </p> <p> <label>密 码:</label> <input name="password" id="password" type="password" title="请输入密码" maxlength="16" value="" /> <input id="rembAccount" name="rembAccount" type="checkbox" value="1" />记住账号 </p> <p> <input name="userlogin" type="submit" alt="登录" value="登录" /> </p> </form> <?php } else { echo "<hr>"; echo "用户$AccountInfoArr[UserID] 登陆成功,<a href=\"$PassportLogoutUrl \">全局退出</a>"; } ?> </div> </div> </body> </html> |
|||
PHP转换对象与数字转换尽量使用内置函数 | php | ||
//对象转换成数组 $arr1 =get_object_vars($object); //数组转换成对象 $obj1=(object)$arr1; |
|||
php实现java的byte数组转换 | php | http://heaven--18.iteye.com/blog/1129735 | |
<?php /** * byte数组与字符串转化类 * @author zikie * Created on 2011-7-15 */ class Bytes { /** * 转换一个String字符串为byte数组 * @param $str 需要转换的字符串 * @param $bytes 目标byte数组 * @author Zikie */ public static function getBytes($str) { $len = strlen($str); $bytes = array(); for($i=0;$i<$len;$i++) { if(ord($str[$i]) >= 128){ $byte = ord($str[$i]) - 256; }else{ $byte = ord($str[$i]); } $bytes[] = $byte ; } return $bytes; } /** * 将字节数组转化为String类型的数据 * @param $bytes 字节数组 * @param $str 目标字符串 * @return 一个String类型的数据 */ public static function toStr($bytes) { $str = ''; foreach($bytes as $ch) { $str .= chr($ch); } return $str; } /** * 转换一个int为byte数组 * @param $byt 目标byte数组 * @param $val 需要转换的字符串 * @author Zikie */ public static function integerToBytes($val) { $byt = array(); $byt[0] = ($val & 0xff); $byt[1] = ($val >> 8 & 0xff); $byt[2] = ($val >> 16 & 0xff); $byt[3] = ($val >> 24 & 0xff); return $byt; } /** * 从字节数组中指定的位置读取一个Integer类型的数据 * @param $bytes 字节数组 * @param $position 指定的开始位置 * @return 一个Integer类型的数据 */ public static function bytesToInteger($bytes, $position) { $val = 0; $val = $bytes[$position + 3] & 0xff; $val <<= 8; $val |= $bytes[$position + 2] & 0xff; $val <<= 8; $val |= $bytes[$position + 1] & 0xff; $val <<= 8; $val |= $bytes[$position] & 0xff; return $val; } /** * 转换一个shor字符串为byte数组 * @param $byt 目标byte数组 * @param $val 需要转换的字符串 * @author Zikie */ public static function shortToBytes($val) { $byt = array(); $byt[0] = ($val & 0xff); $byt[1] = ($val >> 8 & 0xff); return $byt; } /** * 从字节数组中指定的位置读取一个Short类型的数据。 * @param $bytes 字节数组 * @param $position 指定的开始位置 * @return 一个Short类型的数据 */ public static function bytesToShort($bytes, $position) { $val = 0; $val = $bytes[$position + 1] & 0xFF; $val = $val << 8; $val |= $bytes[$position] & 0xFF; return $val; } } ?> |
|||
hash sha1 的问题 | php | ||
$basestr="hello tron"; //需要加载第三方dll,有js实现方式 $Digest = base64_encode(mhash(MHASH_SHA1,$basestr)); //以下三个值是一样的 base64_encode(mhash(MHASH_SHA1,$basestr)) base64_encode(pack("H*",sha1($basestr)) base64_encode(sha1($basestr,TRUE)) //结果不同于以下两种 $Digest = base64_encode(sha1($basestr)); //以下两种结果是一样的 $Digest = base64_encode(sha1($basestr)); $Digest = base64_encode(hash('sha1',$basestr)); |
|||
JS获取客户端系统信息 | web前端 | ||
function getSysInfo() { var ua = navigator.userAgent.toLowerCase(); isWin7 = ua.indexOf("nt 6.1") > -1 isVista = ua.indexOf("nt 6.0") > -1 isWin2003 = ua.indexOf("nt 5.2") > -1 isWinXp = ua.indexOf("nt 5.1") > -1 isWin2000 = ua.indexOf("nt 5.0") > -1 isWindows = (ua.indexOf("windows") != -1 || ua.indexOf("win32") != -1) isMac = (ua.indexOf("macintosh") != -1 || ua.indexOf("mac os x") != -1) isAir = (ua.indexOf("adobeair") != -1) isLinux = (ua.indexOf("linux") != -1) var broser = ""; if (isWin7) { sys = "Windows 7"; } else if (isVista) { sys = "Vista"; } else if (isWinXp) { sys = "Windows xp"; } else if (isWin2003) { sys = "Windows 2003"; } else if (isWin2000) { sys = "Windows 2000"; } else if (isWindows) { sys = "Windows"; } else if (isMac) { sys = "Macintosh"; } else if (isAir) { sys = "Adobeair"; } else if (isLinux) { sys = "Linux"; } else { sys = "Unknow"; } return sys; } |
|||
获取链接地址中某个参数的值 | web前端 | ||
function request(url, paras) { var paraString = url.substring(url.indexOf("?") + 1, url.length).split("&"); var paraObj = {} for (i = 0; j = paraString[i]; i++) { paraObj[j.substring(0, j.indexOf("=")).toLowerCase()] = j.substring(j.indexOf("=") + 1, j.length); } var returnValue = paraObj[paras.toLowerCase()]; if (typeof (returnValue) == "undefined") { return ""; } else { return returnValue; } } |
|||
获取网址根目录 | web前端 | ||
function getRootPath() { return window.location.protocol + "//" + window.location.host + "/"; } |
|||
JS获取浏览器版本 | web前端 | ||
function GetBrowserVersion() { var ua = navigator.userAgent.toLowerCase(); if (ua == null) return "null"; else if (ua.indexOf('chrome') != -1) return ua.substring(ua.indexOf('chrome') + 7, ua.length).split(' ')[0]; else if (ua.indexOf('opera') != -1) return ua.substring(ua.indexOf('version') + 8, ua.length); else if (ua.indexOf('msie') != -1) return ua.substring(ua.indexOf('msie') + 5, ua.length - 1).split(';')[0]; else if (ua.indexOf('safari') != -1) return ua.substring(ua.indexOf('safari') + 7, ua.length); else if (ua.indexOf('gecko') != -1) return ua.substring(ua.indexOf('firefox') + 8, ua.length); else return "null"; } |
|||
修改apache默认首页 | apache 配置 | ||
windows apache <Directory "your www dir"> Options Indexes FollowSymLinks Includes ExecCGI AllowOverride All Order allow,deny Allow from all AddType application/x-httpd-php .php DirectoryIndex yourpagename.php </Directory> 重启apache linux /etc/httpd/conf.d/php.conf 有这个文件? 如果已经在/etc/httpd/conf/httpd.conf中 设置了:DirecotryIndex index.html index.htm index.php 就把DirectoryIndex index.php,这一行换成所需,然后重启apache即可。 |
|||
客户端系统浏览器简洁识别 | php | ||
$visitor = array(); $visitor['agent'] = $_SERVER['HTTP_USER_AGENT']; if (strexists($visitor['agent'], 'Netscape')) { $visitor['browser'] = 'Netscape'; } elseif (strexists($visitor['agent'], 'Lynx')) { $visitor['browser'] = 'Lynx'; } elseif (strexists($visitor['agent'], 'Opera')) { $visitor['browser'] = 'Opera'; } elseif (strexists($visitor['agent'], 'Konqueror')) { $visitor['browser'] = 'Konqueror'; } elseif (strexists($visitor['agent'], 'MSIE')) { $visitor['browser'] = 'MSIE'; } elseif (strexists($visitor['agent'], 'Firefox')) { $visitor['browser'] = 'Firefox'; } elseif (strexists($visitor['agent'], 'Safari')) { $visitor['browser'] = 'Safari'; } elseif (substr($visitor['agent'], 0, 7) == 'Mozilla') { $visitor['browser'] = 'Mozilla'; } else { $visitor['browser'] = 'Other'; } if (strexists($visitor['agent'], 'Win')) { $visitor['os'] = 'Windows'; } elseif (strexists($visitor['agent'], 'Mac')) { $visitor['os'] = 'Mac'; } elseif (strexists($visitor['agent'], 'Linux')) { $visitor['os'] = 'Linux'; } elseif (strexists($visitor['agent'], 'FreeBSD')) { $visitor['os'] = 'FreeBSD'; } elseif (strexists($visitor['agent'], 'SunOS')) { $visitor['os'] = 'SunOS'; } elseif (strexists($visitor['agent'], 'OS/2')) { $visitor['os'] = 'OS/2'; } elseif (strexists($visitor['agent'], 'AIX')) { $visitor['os'] = 'AIX'; } elseif (preg_match("/(Bot|Crawl|Spider)/i", $visitor['agent'])) { $visitor['os'] = 'Spiders'; } else { $visitor['os'] = 'Other'; } print_r("<pre>"); print_r($visitor); function strexists($haystack, $needle) { return!(strpos($haystack, $needle) === FALSE); } |
|||
统一管理 post get cookie file | php | ||
$_G = array(); define('MAGIC_QUOTES_GPC', function_exists('get_magic_quotes_gpc') && get_magic_quotes_gpc()); if (!MAGIC_QUOTES_GPC) { $_GET = daddslashes($_GET); $_POST = daddslashes($_POST); $_COOKIE = daddslashes($_COOKIE); $_FILES = daddslashes($_FILES); } foreach (array_merge($_POST, $_GET) as $k => $v) { $_G['gp_' . $k] = $v; } |
|||
JS自动获取客户端地址来源 | web前端 | ||
<html> <head> <title>获取ip地址</title> <script src="http://fw.qq.com/ipaddress" type="text/javascript"></script> <script type="text/javascript"> function showip(){ alert(IPData[0]) } </script> </head> <body onload="showip()"> 还有新浪的 api json格式输出 http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=js </body> </html> |
|||
简洁分页 | php | ||
/* * 分页函数 * $pagesize 每页数 * $totalcount 总数 * $page 当前页码 * $gourl 翻页地址 至少包含参数 page= * $mode 分页样式 1无上下页,2有上下页,3,4,5.. */ function getPageBreak($pagesize, $totalcount, $page, $gourl, $mode = '1') { $pbreak = ""; $curpage = empty ( $page ) ? 1 : intval ( $page ); $allpage = ceil ( $totalcount / $pagesize ); if ($allpage < 2) { $pbreak .= ''; return $pbreak; } $pbreak .= "<span class='disabled'> {$page} / {$allpage}</span> "; $listsize = 5; $total_list = $listsize * 2 + 1; $totalpage = $allpage; $listdd = ''; if ($mode == '2') { if ($curpage - 1 > 0) { $pbreak .= "<a href='" . $gourl . ($curpage - 1) . "'>上一页</a>"; } } if ($curpage >= $total_list) { $j = $curpage - $listsize; $total_list = $curpage + $listsize; if ($total_list > $totalpage) { $total_list = $totalpage; } } else { $j = 1; if ($total_list > $totalpage) $total_list = $totalpage; } for($j; $j <= $total_list; $j ++) { $pbreak .= ($j == $curpage ? "<span class='current'>$j</span>" : "<a href='{$gourl}{$j}'>{$j}</a>"); } if ($mode == '2') { if ($curpage +1 <= $totalpage) { $pbreak .= "<a href='" . $gourl . ($curpage +1) . "' >下一页</a>"; } } return $pbreak; } |
|||
图片延迟加载 | web前端 | ||
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>图片延迟加载</title> </head> <body> <div id="frame-800-new" class="mqtop10px"> <ul id="new-arrival-title"> <h3 class="all-box-title-left">精品推荐 PICK UP</h3> <li id="new-arrival-num"><span class="activate">1</span></li> </ul> <ul id="new-arrival-box"> <li><a href="http://shop.1626.com/fast.php#page9" target="_blank" title="SLOW.SHOT page9"><img src="data/afficheimg/1314935452543664047.jpg" width="240" height="338" /> <h2>SLOW.SHOT page9</h2> </a></li> <li><a href="http://shop.1626.com/fast.php#page2" target="_blank" title="PDD page2"><img src="data/afficheimg/1314934898531329524.jpg" width="240" height="338" /> <h2>PDD page2</h2> </a></li> <li><a href="http://shop.1626.com/fast.php#page6" target="_blank" title="new come up page6"><img src="data/afficheimg/1314935502892023061.jpg" width="240" height="338" /> <h2>new come up page6</h2> </a></li> <li><a href="http://shop.1626.com/fast.php#page8" target="_blank" title="LEVVV page8"><img src="themes/default/images/delay.gif" srcdelay="data/afficheimg/1314934994661118632.jpg" width="240" height="338" /> <h2>LEVVV page8</h2> </a></li> <li><a href="http://shop.1626.com/fast.php#page4" target="_blank" title="LEVVV EKHLAS page4"><img src="themes/default/images/delay.gif" srcdelay="data/afficheimg/1314935096142741195.jpg" width="240" height="338" /> <h2>LEVVV EKHLAS page4</h2> </a></li> <li><a href="http://shop.1626.com/activity/fast/index.html" target="_blank" title="HJM广告片"><img src="themes/default/images/delay.gif" srcdelay="data/afficheimg/1314952857867328345.jpg" width="240" height="338" /> <h2>HJM广告片</h2> </a></li> <li><a href="http://shop.1626.com/activity/fast/index.html" target="_blank" title="HJM包广告片"><img src="themes/default/images/delay.gif" srcdelay="data/afficheimg/1314953223676849729.jpg" width="240" height="338" /> <h2>HJM包广告片</h2> </a></li> <li><a href="http://shop.1626.com/activity/fast/index.html" target="_blank" title="HJM鞋"><img src="themes/default/images/delay.gif" srcdelay="data/afficheimg/1314953242789605607.jpg" width="240" height="338" /> <h2>HJM鞋</h2> </a></li> </ul> </div> <script type="text/javascript"> //图片延迟加载 function getDomAbsTop(dom){ if(!dom){return null;} var offsetTop=dom.offsetTop; while(dom=dom.offsetParent){ offsetTop+=dom.offsetTop; } return offsetTop; } function delayload(offsetH){ if(!window._imageLoaderMap){ window._imageLoaderMap={ dCount:0, body_cache:document.body, doe_cache:document.compatMode=='BackCompat'?body_cache:document.documentElement, allImage:document.images, loadList:{} }; } if(offsetH || offsetH==0){ var _o=window._imageLoaderMap; var _i=_o.allImage; _o.loadList={}; for(var i=0;i<_i.length;i++){ if((typeof(_i[i])=="object") && _i[i].getAttribute("srcdelay") ){ var _index=getDomAbsTop(_i[i]); _index=_index>offsetH?(_index-offsetH):0; (_o.loadList[_index])?_o.loadList[_index].push(_i[i]):_o.loadList[_index]=[_i[i]]; _o.dCount++; } } } var _o=window._imageLoaderMap; if(_o.dCount<1){return;} var offsetH= Math.max(_o.body_cache.scrollTop,_o.doe_cache.scrollTop); var visioH=offsetH+_o.doe_cache.clientHeight; for(var i in _o.loadList){ if(visioH>i){ for(var l=0;l<_o.loadList[i].length;l++){ _o.loadList[i][l].src=_o.loadList[i][l].getAttribute("srcdelay"); _o.loadList[i][l].removeAttribute("srcdelay"); } delete _o.loadList[i]; _o.dCount--; } } var st = setTimeout(delayload,100); } delayload(500); </script> </body> </html> |
|||
memcache 可视化 | memcache | ||
<?php /* +----------------------------------------------------------------------+ | PHP Version 5 | +----------------------------------------------------------------------+ | Copyright (c) 1997-2004 The PHP Group | +----------------------------------------------------------------------+ | This source file is subject to version 3.0 of the PHP license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.php.net/license/3_0.txt. | | If you did not receive a copy of the PHP license and are unable to | | obtain it through the world-wide-web, please send a note to | | license@php.net so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Authors: Antony Dovgal <tony2001@phpclub.net> | | Mikael Johansson <mikael AT synd DOT info> | | Harun Yayli <harunyayli at gmail.com> | +----------------------------------------------------------------------+ */ $VERSION='$Id: memcache.php,v 0.2 2008/06/02 Exp $'; define('ADMIN_USERNAME','admin'); // Admin Username define('ADMIN_PASSWORD','admin'); // Admin Password define('DATE_FORMAT','Y/m/d H:i:s'); define('GRAPH_SIZE',200); define('MAX_ITEM_DUMP',50); $MEMCACHE_SERVERS[] = '127.0.0.1:11211'; // add more as an array //$MEMCACHE_SERVERS[] = 'mymemcache-server2:11211'; // add more as an array ////////// END OF DEFAULT CONFIG AREA ///////////////////////////////////////////////////////////// ///////////////// Password protect //////////////////////////////////////////////////////////////// if (!isset($_SERVER['PHP_AUTH_USER']) || !isset($_SERVER['PHP_AUTH_PW']) || $_SERVER['PHP_AUTH_USER'] != ADMIN_USERNAME ||$_SERVER['PHP_AUTH_PW'] != ADMIN_PASSWORD) { Header("WWW-Authenticate: Basic realm=\"APC Login admin/admin \""); Header("HTTP/1.0 401 Unauthorized"); echo <<<EOB <html><body> <h1>Rejected!</h1> <big>Wrong Username or Password!</big> </body></html> EOB; exit; } ///////////MEMCACHE FUNCTIONS ///////////////////////////////////////////////////////////////////// function sendMemcacheCommands($command){ global $MEMCACHE_SERVERS; $result = array(); foreach($MEMCACHE_SERVERS as $server){ $strs = explode(':',$server); $host = $strs[0]; $port = $strs[1]; $result[$server] = sendMemcacheCommand($host,$port,$command); } return $result; } function sendMemcacheCommand($server,$port,$command){ $s = fsockopen($server,$port); if (!$s){ die("Cant connect to:".$server.':'.$port); } fwrite($s, $command."\r\n"); $buf=''; while (!feof($s) && strpos($buf,"END\r\n")===false) { $buf .= fgets($s, 256); } fclose($s); return parseMemcacheResults($buf); } function parseMemcacheResults($str){ $res = array(); $lines = explode("\r\n",$str); $cnt = count($lines); for($i=0; $i< $cnt; $i++){ $line = $lines[$i]; $l = explode(' ',$line,3); if (count($l)==3){ $res[$l[0]][$l[1]]=$l[2]; if ($l[0]=='VALUE'){ // next line is the value $res[$l[0]][$l[1]] = array(); list ($flag,$size)=explode(' ',$l[2]); $res[$l[0]][$l[1]]['stat']=array('flag'=>$flag,'size'=>$size); $res[$l[0]][$l[1]]['value']=$lines[++$i]; } } } return $res; } function dumpCacheSlab($server,$slabId,$limit){ list($host,$port) = explode(':',$server); $resp = sendMemcacheCommand($host,$port,'stats cachedump '.$slabId.' '.$limit); return $resp; } function getCacheItems(){ $items = sendMemcacheCommands('stats items'); $serverItems = array(); $totalItems = array(); foreach ($items as $server=>$itemlist){ $serverItems[$server] = array(); $totalItems[$server]=0; if (!isset($itemlist['STAT'])){ continue; } $iteminfo = $itemlist['STAT']; foreach($iteminfo as $keyinfo=>$value){ if (preg_match('/items\:(\d+?)\:(.+?)$/',$keyinfo,$matches)){ $serverItems[$server][$matches[1]][$matches[2]] = $value; if ($matches[2]=='number'){ $totalItems[$server] +=$value; } } } } return array('items'=>$serverItems,'counts'=>$totalItems); } function getMemcacheStats($total=true){ $resp = sendMemcacheCommands('stats'); if ($total){ $res = array(); foreach($resp as $server=>$r){ foreach($r['STAT'] as $key=>$row){ if (!isset($res[$key])){ $res[$key]=null; } switch ($key){ case 'pid': $res['pid'][$server]=$row; break; case 'uptime': $res['uptime'][$server]=$row; break; case 'time': $res['time'][$server]=$row; break; case 'version': $res['version'][$server]=$row; break; case 'pointer_size': $res['pointer_size'][$server]=$row; break; case 'rusage_user': $res['rusage_user'][$server]=$row; break; case 'rusage_system': $res['rusage_system'][$server]=$row; break; case 'curr_items': $res['curr_items']+=$row; break; case 'total_items': $res['total_items']+=$row; break; case 'bytes': $res['bytes']+=$row; break; case 'curr_connections': $res['curr_connections']+=$row; break; case 'total_connections': $res['total_connections']+=$row; break; case 'connection_structures': $res['connection_structures']+=$row; break; case 'cmd_get': $res['cmd_get']+=$row; break; case 'cmd_set': $res['cmd_set']+=$row; break; case 'get_hits': $res['get_hits']+=$row; break; case 'get_misses': $res['get_misses']+=$row; break; case 'evictions': $res['evictions']+=$row; break; case 'bytes_read': $res['bytes_read']+=$row; break; case 'bytes_written': $res['bytes_written']+=$row; break; case 'limit_maxbytes': $res['limit_maxbytes']+=$row; break; case 'threads': $res['rusage_system'][$server]=$row; break; } } } return $res; } return $resp; } ////////////////////////////////////////////////////// // // don't cache this page // header("Cache-Control: no-store, no-cache, must-revalidate"); // HTTP/1.1 header("Cache-Control: post-check=0, pre-check=0", false); header("Pragma: no-cache"); // HTTP/1.0 function duration($ts) { global $time; $years = (int)((($time - $ts)/(7*86400))/52.177457); $rem = (int)(($time-$ts)-($years * 52.177457 * 7 * 86400)); $weeks = (int)(($rem)/(7*86400)); $days = (int)(($rem)/86400) - $weeks*7; $hours = (int)(($rem)/3600) - $days*24 - $weeks*7*24; $mins = (int)(($rem)/60) - $hours*60 - $days*24*60 - $weeks*7*24*60; $str = ''; if($years==1) $str .= "$years year, "; if($years>1) $str .= "$years years, "; if($weeks==1) $str .= "$weeks week, "; if($weeks>1) $str .= "$weeks weeks, "; if($days==1) $str .= "$days day,"; if($days>1) $str .= "$days days,"; if($hours == 1) $str .= " $hours hour and"; if($hours>1) $str .= " $hours hours and"; if($mins == 1) $str .= " 1 minute"; else $str .= " $mins minutes"; return $str; } // create graphics // function graphics_avail() { return extension_loaded('gd'); } function bsize($s) { foreach (array('','K','M','G') as $i => $k) { if ($s < 1024) break; $s/=1024; } return sprintf("%5.1f %sBytes",$s,$k); } // create menu entry function menu_entry($ob,$title) { global $PHP_SELF; if ($ob==$_GET['op']){ return "<li><a class=\"child_active\" href=\"$PHP_SELF&op=$ob\">$title</a></li>"; } return "<li><a class=\"active\" href=\"$PHP_SELF&op=$ob\">$title</a></li>"; } function getHeader(){ $header = <<<EOB <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head><title>MEMCACHE INFO</title> <style type="text/css"><!-- body { background:white; font-size:100.01%; margin:0; padding:0; } body,p,td,th,input,submit { font-size:0.8em;font-family:arial,helvetica,sans-serif; } * html body {font-size:0.8em} * html p {font-size:0.8em} * html td {font-size:0.8em} * html th {font-size:0.8em} * html input {font-size:0.8em} * html submit {font-size:0.8em} td { vertical-align:top } a { color:black; font-weight:none; text-decoration:none; } a:hover { text-decoration:underline; } div.content { padding:1em 1em 1em 1em; position:absolute; ; z-index:100; } h1.memcache { background:rgb(153,153,204); margin:0; padding:0.5em 1em 0.5em 1em; } * html h1.memcache { margin-bottom:-7px; } h1.memcache a:hover { text-decoration:none; color:rgb(90,90,90); } h1.memcache span.logo { background:rgb(119,123,180); color:black; border-right: solid black 1px; border-bottom: solid black 1px; font-style:italic; font-size:1em; padding-left:1.2em; padding-right:1.2em; text-align:right; display:block; ; } h1.memcache span.logo span.name { color:white; font-size:0.7em; padding:0 0.8em 0 2em; } h1.memcache span.nameinfo { color:white; display:inline; font-size:0.4em; margin-left: 3em; } h1.memcache div.copy { color:black; font-size:0.4em; position:absolute; right:1em; } hr.memcache { background:white; border-bottom:solid rgb(102,102,153) 1px; border-style:none; border-top:solid rgb(102,102,153) 10px; height:12px; margin:0; margin-top:1px; padding:0; } ol,menu { margin:1em 0 0 0; padding:0.2em; margin-left:1em;} ol.menu li { display:inline; margin-right:0.7em; list-style:none; font-size:85%} ol.menu a { background:rgb(153,153,204); border:solid rgb(102,102,153) 2px; color:white; font-weight:bold; margin-right:0em; padding:0.1em 0.5em 0.1em 0.5em; text-decoration:none; margin-left: 5px; } ol.menu a.child_active { background:rgb(153,153,204); border:solid rgb(102,102,153) 2px; color:white; font-weight:bold; margin-right:0em; padding:0.1em 0.5em 0.1em 0.5em; text-decoration:none; border-left: solid black 5px; margin-left: 0px; } ol.menu span.active { background:rgb(153,153,204); border:solid rgb(102,102,153) 2px; color:black; font-weight:bold; margin-right:0em; padding:0.1em 0.5em 0.1em 0.5em; text-decoration:none; border-left: solid black 5px; } ol.menu span.inactive { background:rgb(193,193,244); border:solid rgb(182,182,233) 2px; color:white; font-weight:bold; margin-right:0em; padding:0.1em 0.5em 0.1em 0.5em; text-decoration:none; margin-left: 5px; } ol.menu a:hover { background:rgb(193,193,244); text-decoration:none; } div.info { background:rgb(204,204,204); border:solid rgb(204,204,204) 1px; margin-bottom:1em; } div.info h2 { background:rgb(204,204,204); color:black; font-size:1em; margin:0; padding:0.1em 1em 0.1em 1em; } div.info table { border:solid rgb(204,204,204) 1px; border-spacing:0; ; } div.info table th { background:rgb(204,204,204); color:white; margin:0; padding:0.1em 1em 0.1em 1em; } div.info table th a.sortable { color:black; } div.info table tr.tr-0 { background:rgb(238,238,238); } div.info table tr.tr-1 { background:rgb(221,221,221); } div.info table td { padding:0.3em 1em 0.3em 1em; } div.info table td.td-0 { border-right:solid rgb(102,102,153) 1px; white-space:nowrap; } div.info table td.td-n { border-right:solid rgb(102,102,153) 1px; } div.info table td h3 { color:black; font-size:1.1em; margin-left:-0.3em; } .td-0 a , .td-n a, .tr-0 a , tr-1 a { text-decoration:underline; } div.graph { margin-bottom:1em } div.graph h2 { background:rgb(204,204,204);; color:black; font-size:1em; margin:0; padding:0.1em 1em 0.1em 1em; } div.graph table { border:solid rgb(204,204,204) 1px; color:black; font-weight:normal; ; } div.graph table td.td-0 { background:rgb(238,238,238); } div.graph table td.td-1 { background:rgb(221,221,221); } div.graph table td { padding:0.2em 1em 0.4em 1em; } div.div1,div.div2 { margin-bottom:1em; ; } div.div3 { position:absolute; left:40em; top:1em; ; } //div.div3 { position:absolute; left:37em; top:1em; right:1em; } div.sorting { margin:1.5em 0em 1.5em 2em } .center { text-align:center } .aright { position:absolute;right:1em } .right { text-align:right } .ok { color:rgb(0,200,0); font-weight:bold} .failed { color:rgb(200,0,0); font-weight:bold} span.box { border: black solid 1px; border-right:solid black 2px; border-bottom:solid black 2px; padding:0 0.5em 0 0.5em; margin-right:1em; } span.green { background:#60F060; padding:0 0.5em 0 0.5em} span.red { background:#D06030; padding:0 0.5em 0 0.5em } div.authneeded { background:rgb(238,238,238); border:solid rgb(204,204,204) 1px; color:rgb(200,0,0); font-size:1.2em; font-weight:bold; padding:2em; text-align:center; } input { background:rgb(153,153,204); border:solid rgb(102,102,153) 2px; color:white; font-weight:bold; margin-right:1em; padding:0.1em 0.5em 0.1em 0.5em; } //--> </style> </head> <body> <div class="head"> <h1 class="memcache"> <span class="logo"><a href="http://pecl.php.net/package/memcache">memcache</a></span> <span class="nameinfo">memcache.php by <a href="http://livebookmark.net">Harun Yayli</a></span> </h1> <hr class="memcache"> </div> <div class=content> EOB; return $header; } function getFooter(){ $footer = '</div><!-- Based on apc.php --></body> </html> '; return $footer; } function getMenu(){ global $PHP_SELF; echo "<ol class=menu>"; if ($_GET['op']!=4){ echo <<<EOB <li><a href="$PHP_SELF&op={$_GET['op']}">Refresh Data</a></li> EOB; } else { echo <<<EOB <li><a href="$PHP_SELF&op=2}">Back</a></li> EOB; } echo menu_entry(1,'View Host Stats'), menu_entry(2,'Variables'); echo <<<EOB </ol> <br/> EOB; } // TODO, AUTH $_GET['op'] = !isset($_GET['op'])? '1':$_GET['op']; $PHP_SELF= isset($_SERVER['PHP_SELF']) ? htmlentities(strip_tags($_SERVER['PHP_SELF'],'')) : ''; $PHP_SELF=$PHP_SELF.'?'; $time = time(); // sanitize _GET foreach($_GET as $key=>$g){ $_GET[$key]=htmlentities($g); } // singleout // when singleout is set, it only gives details for that server. if (isset($_GET['singleout']) && $_GET['singleout']>=0 && $_GET['singleout'] <count($MEMCACHE_SERVERS)){ $MEMCACHE_SERVERS = array($MEMCACHE_SERVERS[$_GET['singleout']]); } // display images if (isset($_GET['IMG'])){ $memcacheStats = getMemcacheStats(); $memcacheStatsSingle = getMemcacheStats(false); if (!graphics_avail()) { exit(0); } function fill_box($im, $x, $y, $w, $h, $color1, $color2,$text='',$placeindex='') { global $col_black; $x1=$x+$w-1; $y1=$y+$h-1; imagerectangle($im, $x, $y1, $x1+1, $y+1, $col_black); if($y1>$y) imagefilledrectangle($im, $x, $y, $x1, $y1, $color2); else imagefilledrectangle($im, $x, $y1, $x1, $y, $color2); imagerectangle($im, $x, $y1, $x1, $y, $color1); if ($text) { if ($placeindex>0) { if ($placeindex<16) { $px=5; $py=$placeindex*12+6; imagefilledrectangle($im, $px+90, $py+3, $px+90-4, $py-3, $color2); imageline($im,$x,$y+$h/2,$px+90,$py,$color2); imagestring($im,2,$px,$py-6,$text,$color1); } else { if ($placeindex<31) { $px=$x+40*2; $py=($placeindex-15)*12+6; } else { $px=$x+40*2+100*intval(($placeindex-15)/15); $py=($placeindex%15)*12+6; } imagefilledrectangle($im, $px, $py+3, $px-4, $py-3, $color2); imageline($im,$x+$w,$y+$h/2,$px,$py,$color2); imagestring($im,2,$px+2,$py-6,$text,$color1); } } else { imagestring($im,4,$x+5,$y1-16,$text,$color1); } } } function fill_arc($im, $centerX, $centerY, $diameter, $start, $end, $color1,$color2,$text='',$placeindex=0) { $r=$diameter/2; $w=deg2rad((360+$start+($end-$start)/2)%360); if (function_exists("imagefilledarc")) { // exists only if GD 2.0.1 is avaliable imagefilledarc($im, $centerX+1, $centerY+1, $diameter, $diameter, $start, $end, $color1, IMG_ARC_PIE); imagefilledarc($im, $centerX, $centerY, $diameter, $diameter, $start, $end, $color2, IMG_ARC_PIE); imagefilledarc($im, $centerX, $centerY, $diameter, $diameter, $start, $end, $color1, IMG_ARC_NOFILL|IMG_ARC_EDGED); } else { imagearc($im, $centerX, $centerY, $diameter, $diameter, $start, $end, $color2); imageline($im, $centerX, $centerY, $centerX + cos(deg2rad($start)) * $r, $centerY + sin(deg2rad($start)) * $r, $color2); imageline($im, $centerX, $centerY, $centerX + cos(deg2rad($start+1)) * $r, $centerY + sin(deg2rad($start)) * $r, $color2); imageline($im, $centerX, $centerY, $centerX + cos(deg2rad($end-1)) * $r, $centerY + sin(deg2rad($end)) * $r, $color2); imageline($im, $centerX, $centerY, $centerX + cos(deg2rad($end)) * $r, $centerY + sin(deg2rad($end)) * $r, $color2); imagefill($im,$centerX + $r*cos($w)/2, $centerY + $r*sin($w)/2, $color2); } if ($text) { if ($placeindex>0) { imageline($im,$centerX + $r*cos($w)/2, $centerY + $r*sin($w)/2,$diameter, $placeindex*12,$color1); imagestring($im,4,$diameter, $placeindex*12,$text,$color1); } else { imagestring($im,4,$centerX + $r*cos($w)/2, $centerY + $r*sin($w)/2,$text,$color1); } } } $size = GRAPH_SIZE; // image size $image = imagecreate($size+50, $size+10); $col_white = imagecolorallocate($image, 0xFF, 0xFF, 0xFF); $col_red = imagecolorallocate($image, 0xD0, 0x60, 0x30); $col_green = imagecolorallocate($image, 0x60, 0xF0, 0x60); $col_black = imagecolorallocate($image, 0, 0, 0); imagecolortransparent($image,$col_white); switch ($_GET['IMG']){ case 1: // pie chart $tsize=$memcacheStats['limit_maxbytes']; $avail=$tsize-$memcacheStats['bytes']; $x=$y=$size/2; $angle_from = 0; $fuzz = 0.000001; foreach($memcacheStatsSingle as $serv=>$mcs) { // print_r($mcs); $free = $mcs['STAT']['limit_maxbytes']-$mcs['STAT']['bytes']; $used = $mcs['STAT']['bytes']; if ($free>0){ // draw free $angle_to = ($free*360)/$tsize; $perc =sprintf("%.2f%%", ($free *100) / $tsize) ; fill_arc($image,$x,$y,$size,$angle_from,$angle_from + $angle_to ,$col_black,$col_green,$perc); $angle_from = $angle_from + $angle_to ; } if ($used>0){ // draw used $angle_to = ($used*360)/$tsize; $perc =sprintf("%.2f%%", ($used *100) / $tsize) ; // echo 'Used:(',$used,'/',$tsize,')',$angle_from,':',$angle_from + $angle_to,"\n"; fill_arc($image,$x,$y,$size,$angle_from,$angle_from + $angle_to ,$col_black,$col_red, '('.$perc.')' ); $angle_from = $angle_from+ $angle_to ; } } break; case 2: // hit miss $hits = ($memcacheStats['get_hits']==0) ? 1:$memcacheStats['get_hits']; $misses = ($memcacheStats['get_misses']==0) ? 1:$memcacheStats['get_misses']; $total = $hits + $misses ; fill_box($image, 30,$size,50,-$hits*($size-21)/$total,$col_black,$col_green,sprintf("%.1f%%",$hits*100/$total)); fill_box($image,130,$size,50,-max(4,($total-$hits)*($size-21)/$total),$col_black,$col_red,sprintf("%.1f%%",$misses*100/$total)); break; } header("Content-type: image/png"); imagepng($image); exit; } echo getHeader(); echo getMenu(); switch ($_GET['op']) { case 1: // host stats $phpversion = phpversion(); $memcacheStats = getMemcacheStats(); $memcacheStatsSingle = getMemcacheStats(false); $mem_size = $memcacheStats['limit_maxbytes']; $mem_used = $memcacheStats['bytes']; $mem_avail= $mem_size-$mem_used; $startTime = time()-array_sum($memcacheStats['uptime']); $curr_items = $memcacheStats['curr_items']; $total_items = $memcacheStats['total_items']; $hits = ($memcacheStats['get_hits']==0) ? 1:$memcacheStats['get_hits']; $misses = ($memcacheStats['get_misses']==0) ? 1:$memcacheStats['get_misses']; $sets = $memcacheStats['cmd_set']; $req_rate = sprintf("%.2f",($hits+$misses)/($time-$startTime)); $hit_rate = sprintf("%.2f",($hits)/($time-$startTime)); $miss_rate = sprintf("%.2f",($misses)/($time-$startTime)); $set_rate = sprintf("%.2f",($sets)/($time-$startTime)); echo <<< EOB <div class="info div1"><h2>General Cache Information</h2> <table cellspacing=0><tbody> <tr class=tr-1><td class=td-0>PHP Version</td><td>$phpversion</td></tr> EOB; echo "<tr class=tr-0><td class=td-0>Memcached Host". ((count($MEMCACHE_SERVERS)>1) ? 's':'')."</td><td>"; $i=0; if (!isset($_GET['singleout']) && count($MEMCACHE_SERVERS)>1){ foreach($MEMCACHE_SERVERS as $server){ echo ($i+1).'. <a href="'.$PHP_SELF.'&singleout='.$i++.'">'.$server.'</a><br/>'; } } else{ echo '1.'.$MEMCACHE_SERVERS[0]; } if (isset($_GET['singleout'])){ echo '<a href="'.$PHP_SELF.'">(all servers)</a><br/>'; } echo "</td></tr>\n"; echo "<tr class=tr-1><td class=td-0>Total Memcache Cache</td><td>".bsize($memcacheStats['limit_maxbytes'])."</td></tr>\n"; echo <<<EOB </tbody></table> </div> <div class="info div1"><h2>Memcache Server Information</h2> EOB; foreach($MEMCACHE_SERVERS as $server){ echo '<table cellspacing=0><tbody>'; echo '<tr class=tr-1><td class=td-1 colspan="2">'.$server.'</td></tr>'; echo '<tr class=tr-0><td class=td-0>Start Time</td><td>',date(DATE_FORMAT,$memcacheStatsSingle[$server]['STAT']['time']-$memcacheStatsSingle[$server]['STAT']['uptime']),'</td></tr>'; echo '<tr class=tr-1><td class=td-0>Uptime</td><td>',duration($memcacheStatsSingle[$server]['STAT']['time']-$memcacheStatsSingle[$server]['STAT']['uptime']),'</td></tr>'; echo '<tr class=tr-0><td class=td-0>Memcached Server Version</td><td>'.$memcacheStatsSingle[$server]['STAT']['version'].'</td></tr>'; echo '<tr class=tr-1><td class=td-0>Used Cache Size</td><td>',bsize($memcacheStatsSingle[$server]['STAT']['bytes']),'</td></tr>'; echo '<tr class=tr-0><td class=td-0>Total Cache Size</td><td>',bsize($memcacheStatsSingle[$server]['STAT']['limit_maxbytes']),'</td></tr>'; echo '</tbody></table>'; } echo <<<EOB </div> <div class="graph div3"><h2>Host Status Diagrams</h2> <table cellspacing=0><tbody> EOB; $size=''.(GRAPH_SIZE+50).' height='.(GRAPH_SIZE+10); echo <<<EOB <tr> <td class=td-0>Cache Usage</td> <td class=td-1>Hits & Misses</td> </tr> EOB; echo graphics_avail() ? '<tr>'. "<td class=td-0><img alt=\"\" $size src=\"$PHP_SELF&IMG=1&".(isset($_GET['singleout'])? 'singleout='.$_GET['singleout'].'&':'')."$time\"></td>". "<td class=td-1><img alt=\"\" $size src=\"$PHP_SELF&IMG=2&".(isset($_GET['singleout'])? 'singleout='.$_GET['singleout'].'&':'')."$time\"></td></tr>\n" : "", '<tr>', '<td class=td-0><span class="green box"> </span>Free: ',bsize($mem_avail).sprintf(" (%.1f%%)",$mem_avail*100/$mem_size),"</td>\n", '<td class=td-1><span class="green box"> </span>Hits: ',$hits.sprintf(" (%.1f%%)",$hits*100/($hits+$misses)),"</td>\n", '</tr>', '<tr>', '<td class=td-0><span class="red box"> </span>Used: ',bsize($mem_used ).sprintf(" (%.1f%%)",$mem_used *100/$mem_size),"</td>\n", '<td class=td-1><span class="red box"> </span>Misses: ',$misses.sprintf(" (%.1f%%)",$misses*100/($hits+$misses)),"</td>\n"; echo <<< EOB </tr> </tbody></table> <br/> <div class="info"><h2>Cache Information</h2> <table cellspacing=0><tbody> <tr class=tr-0><td class=td-0>Current Items(total)</td><td>$curr_items ($total_items)</td></tr> <tr class=tr-1><td class=td-0>Hits</td><td>{$hits}</td></tr> <tr class=tr-0><td class=td-0>Misses</td><td>{$misses}</td></tr> <tr class=tr-1><td class=td-0>Request Rate (hits, misses)</td><td>$req_rate cache requests/second</td></tr> <tr class=tr-0><td class=td-0>Hit Rate</td><td>$hit_rate cache requests/second</td></tr> <tr class=tr-1><td class=td-0>Miss Rate</td><td>$miss_rate cache requests/second</td></tr> <tr class=tr-0><td class=td-0>Set Rate</td><td>$set_rate cache requests/second</td></tr> </tbody></table> </div> EOB; break; case 2: // variables $m=0; $cacheItems= getCacheItems(); $items = $cacheItems['items']; $totals = $cacheItems['counts']; $maxDump = MAX_ITEM_DUMP; foreach($items as $server => $entries) { echo <<< EOB <div class="info"><table cellspacing=0><tbody> <tr><th colspan="2">$server</th></tr> <tr><th>Slab Id</th><th>Info</th></tr> EOB; foreach($entries as $slabId => $slab) { $dumpUrl = $PHP_SELF.'&op=2&server='.(array_search($server,$MEMCACHE_SERVERS)).'&dumpslab='.$slabId; echo "<tr class=tr-$m>", "<td class=td-0><center>",'<a href="',$dumpUrl,'">',$slabId,'</a>',"</center></td>", "<td class=td-last><b>Item count:</b> ",$slab['number'],'<br/><b>Age:</b>',duration($time-$slab['age']),'<br/> <b>Evicted:</b>',($slab['evicted']==1? 'Yes':'No'); if ((isset($_GET['dumpslab']) && $_GET['dumpslab']==$slabId) && (isset($_GET['server']) && $_GET['server']==array_search($server,$MEMCACHE_SERVERS))){ echo "<br/><b>Items: item</b><br/>"; $items = dumpCacheSlab($server,$slabId,$slab['number']); // maybe someone likes to do a pagination here :) $i=1; foreach($items['ITEM'] as $itemKey=>$itemInfo){ $itemInfo = trim($itemInfo,'[ ]'); echo '<a href="',$PHP_SELF,'&op=4&server=',(array_search($server,$MEMCACHE_SERVERS)),'&key=',base64_encode($itemKey).'">',$itemKey,'</a>'; if ($i++ % 10 == 0) { echo '<br/>'; } elseif ($i!=$slab['number']+1){ echo ','; } } } echo "</td></tr>"; $m=1-$m; } echo <<<EOB </tbody></table> </div><hr/> EOB; } break; break; case 4: //item dump if (!isset($_GET['key']) || !isset($_GET['server'])){ echo "No key set!"; break; } // I'm not doing anything to check the validity of the key string. // probably an exploit can be written to delete all the files in key=base64_encode("\n\r delete all"). // somebody has to do a fix to this. $theKey = htmlentities(base64_decode($_GET['key'])); $theserver = $MEMCACHE_SERVERS[(int)$_GET['server']]; list($h,$p) = explode(':',$theserver); $r = sendMemcacheCommand($h,$p,'get '.$theKey); echo <<<EOB <div class="info"><table cellspacing=0><tbody> <tr><th>Server<th>Key</th><th>Value</th></tr> EOB; echo "<tr><td class=td-0>",$theserver,"</td><td class=td-0>",$theKey, " <br/>flag:",$r['VALUE'][$theKey]['stat']['flag'], " <br/>Size:",bsize($r['VALUE'][$theKey]['stat']['size']), "</td><td>",chunk_split($r['VALUE'][$theKey]['value'],40),"</td></tr>"; echo <<<EOB </tbody></table> </div><hr/> EOB; break; } echo getFooter(); ?> |