<?php
/**
 * ITlearner PHP探针 v1.0
 * http://www.9enjoy.com/phpcheck/
 * 转载本程序时请保留这些信息
 */
 
//error_reporting(E_ALL);
$author = 'Enjoy';
$ver = 'v1.0';
$script_name = $_SERVER['SCRIPT_NAME'];
$startime = microtime_float();

/**
 * 1 公开$_SERVER、$_COOKIE等全局变量和PHPINFO的显示 0 不公开
 * 如果您不想显示这些信息，可以设置为0关闭。
 */
$flag = 1;

$ac = '';
if(isset($_GET['ac'])){
    $ac = $_GET['ac'];
}

if($ac == 'phpinfo' && $flag){
    phpinfo();
    exit();
}

$dis_fun = ini_get("disable_functions");

if($flag){
    $menu = '<br /><a href="'.$script_name.'?ac=show_var&amp;co=server">查看服务器($_SERVER)变量</a>';
    $menu .= ' | <a href="'.$script_name.'?ac=show_var&amp;co=env">查看环境($_ENV)变量</a>';
    $menu .= ' | <a href="'.$script_name.'?ac=show_var&amp;co=cookie">查看COOKIE</a>';
    if(strpos($dis_fun,"phpinfo")===false){
        $menu .= ' | <a href="'.$script_name.'?ac=phpinfo" target="_blank">查看PHPINFO</a>';
    }
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=GB2312" />
<title>PHP探针(ITlearner PhpCheck) V1.0 - <?php echo php_uname('n'); ?></title>
<style type="text/css">
body		{font-size:12px;margin-left:50px;background:#FFF;line-height:1.5;font-family:宋体,arial;color:#000;}
td,span {font-size:12px;word-wrap:break-word;word-break:break-all;overflow:hidden;line-height:1.2;}
form		{margin:0;}
a       {color:#000;text-decoration:none}
a:hover {color:#F00;text-decoration:underline;}
#hx-top		{width:600px;margin:8px 0;text-align:center;}
#hx-footer	{border:1px dotted #183789;width:598px;margin-top:10px;text-align:center;padding:5px 0;}
h1			{font-size:30px;margin:0;}
h1 sub	{font-size:14px;font-weight:normal;}
.input  {border:1px solid #0099CF;}
.btn_c  {background:#0099CF;border:1px solid #0099CF;color:#FFF;font-size:12px;}
.frame_box{border:0;width:600px;margin-top:5px;clear:both;}
.frame_box h3{background:#0099CF;text-align:center;color:#FFF;padding:3px;font-weight:bold;margin:0;font-size:12px;width:594px;}
.item_content{width:600px;}
.hx_tr1{text-indent:4px;background:#FFF;}
.hx_tr2{background:#FFF;}
.hx_tr3{text-align:center;background:#FFF;height:18px;}
.font_1{color:#888;}
.msgWarn{color:#080;}
.font_3{color:#F00;}
.table1{background:#0099CF;width:600px;border:0;}
.table1 tr{background:#FFF;}
.table1 td{padding-left:4px;}
th{background:#9CF;padding-left:6px;font-weight:normal;text-align:left;}
pre{width:500px;overflow:auto;margin:0;height:80px;}
</style>
</head>
<body>

<a name="top"></a>
<div id="hx-top">
<h1><a href="<?php echo $script_name?>">PHP探针</a><sub> - <a href="http://www.9enjoy.com/phpcheck/" target="_blank"><?php echo $ver?></a>(<a href="http://www.itlearner.com" target="_blank">ITlearner</a>)</sub></h1>
</div>

<div id="menu">
    选项：<a href="<?php echo $script_name?>#hx-server">服务器主要参数</a> | <a href="<?php echo $script_name?>?ac=hx-php">PHP主要参数</a> | <a href="<?php echo $script_name.'?ac=hx-test'?>">服务器性能测试</a><?php echo $menu?>
</div>

<?php

function microtime_float(){
    list($usec, $sec) = explode(" ", microtime());
    return ((float)$usec + (float)$sec);
}

function size_format($bytes,$decimals=2){
	$quant = array(
		'TB' => 1099511627776,  // pow( 1024, 4)
		'GB' => 1073741824,     // pow( 1024, 3)
		'MB' => 1048576,        // pow( 1024, 2)
		'KB' => 1024,           // pow( 1024, 1)
		'B ' => 1,              // pow( 1024, 0)
	);

	foreach ( $quant as $unit => $mag )
		if ( doubleval($bytes) >= $mag )
			return number_format( $bytes / $mag, $decimals ) . ' ' . $unit;

	return false;
}

function get_ini($var){
    switch($res = ini_get($var)){
        case 0: return 'Off 否'; break;
        case 1: return 'On 是'; break;
        default:return $res;
    }
}

if($ac == ''){
    $s = $_SERVER;
    $path_parts = pathinfo($s['DOCUMENT_ROOT'].$script_name);
    $dirname    = $path_parts['dirname'];

function get_linux(){
    global $cpu,$mem,$sys;
    if (false === ($str = @file("/proc/cpuinfo"))) return false;
    $str = implode("", $str);
    @preg_match_all("/model\sname\s+\:(.*)[\r\n]+/isU", $str, $match1);
    @preg_match_all("/cache\ssize\s+:\s*(.*)[\r\n]+/isU", $str, $match2);
    $cpu['num'] = count($match1[1]);
    for($i=0;$i<$cpu['num'];$i++){
        $cpu['model'][] = $match1[1][$i];
        $cpu['cache'][] = $match2[1][$i];
    }
    if($cpu['num']){
        $cpu['model'] = implode("<br />", $cpu['model']);
        $cpu['cache'] = implode("<br />", $cpu['cache']);
    }
	// MEMORY
	if (false === ($str = @file("/proc/meminfo"))) return false;
	$str = implode("", $str);
	preg_match_all("/MemTotal\s{0,}\:+\s{0,}([\d\.]+).+?MemFree\s{0,}\:+\s{0,}([\d\.]+).+?Cached\s{0,}\:+\s{0,}([\d\.]+).+?SwapTotal\s{0,}\:+\s{0,}([\d\.]+).+?SwapFree\s{0,}\:+\s{0,}([\d\.]+)/s", $str, $matches);

	$mem['Total'] = size_format($matches[1][0]*1024);
	$mem['Free'] = size_format($matches[2][0]*1024);
	$mem['Cached'] = size_format($matches[3][0]*1024);
	$mem['SwapTotal'] = size_format($matches[4][0]*1024);
	$mem['SwapFree'] = size_format($matches[5][0]*1024);
	$mem['RealFree'] = size_format(($matches[2][0] + $matches[3][0])*1024);
    $mem['info'] = '物理内存：'.$mem['Total'].'，Swap内存：'.$mem['SwapTotal'].'。<br/>
目前物理内存空闲'.$mem['Free'].'，Swap内存空闲'.$mem['SwapFree'].'。<br/>
已使用的物理内存中，内存缓存有'.$mem['Cached'].'，物理内存实际可用：'.$mem['RealFree'].'。';

	$sys['os'] = php_uname('s').' 版本：'.php_uname('r');
}

function GetWMI($wmi,$strClass, $strValue = array()) {
	$arrData = array();
	$objWEBM = $wmi->Get($strClass);
	$arrProp = $objWEBM->Properties_;
	$arrWEBMCol = $objWEBM->Instances_();
	foreach($arrWEBMCol as $objItem) {
		@reset($arrProp);
		$arrInstance = array();
		foreach($arrProp as $propItem) {
			eval("\$value = \$objItem->" . $propItem->Name . ";");
			if (empty($strValue)) {
				$arrInstance[$propItem->Name] = trim($value);
			} else {
				if (in_array($propItem->Name, $strValue)) {
					$arrInstance[$propItem->Name] = trim($value);
				}
			}
		}
		$arrData[] = $arrInstance;
	}
	return $arrData;
}

function get_win($isapache){
    global $cpu,$sys,$mem;
	if (PHP_VERSION >= 5 && $isapache) {
		$objLocator = new COM("WbemScripting.SWbemLocator");
		$wmi = $objLocator->ConnectServer();
		$prop = $wmi->get("Win32_PnPEntity");
    	$cpuinfo = GetWMI($wmi,"Win32_Processor", array("Name","L2CacheSize","NumberOfCores"));
    	if(isset($cpuinfo[0]['NumberOfCores'])){;
    	    $cpu['num'] = $cpuinfo[0]['NumberOfCores'];
        }else{
    		$cpu['num'] = 1;
    	}
    	for ($i=0;$i<$cpu['num'];$i++){
    		$cpu['model'] .= $cpuinfo[0]['Name']."<br />";
    		$cpu['cache'] .= $cpuinfo[0]['L2CacheSize']." KB<br />";
    	}
    	// SYSINFO
    	$sysinfo = GetWMI($wmi,"Win32_OperatingSystem", array('LastBootUpTime','TotalVisibleMemorySize','FreePhysicalMemory','Caption','CSDVersion','SerialNumber','InstallDate'));
    	$sys['os'] = $sysinfo[0]['Caption']." ".$sysinfo[0]['CSDVersion']."  安装于".date('Y年m月d日H:i:s',strtotime(substr($sysinfo[0]['InstallDate'],0,14)));
    	// MEMORY
	    $mem['Total'] = size_format($sysinfo[0]['TotalVisibleMemorySize']*1024);
	    $mem['Free'] = size_format($sysinfo[0]['FreePhysicalMemory']*1024);
	    $mem['info'] = '物理内存：'.$mem['Total'].'，空闲内存：'.$mem['Free'];

	} else {
        $cpu['model'] = getenv('PROCESSOR_IDENTIFIER')?getenv('PROCESSOR_IDENTIFIER'):'获取失败';
        $cpu['cache'] = '不详';
        $cpu['num'] = getenv('NUMBER_OF_PROCESSORS')?getenv('NUMBER_OF_PROCESSORS'):'获取失败';
        $mem['info'] = '获取失败';
	}
    if(!$sys['os']) $sys['os'] = php_uname('s').' 版本：'.php_uname('r');
}

$cpu = array('model'=>'','cache'=>'');
if(PHP_OS == 'Linux'){
    get_linux();
}elseif(strtoupper(substr(PHP_OS, 0, 3)) === 'WIN'){
    if(strpos(strtolower($s['SERVER_SOFTWARE']),"apache")!==false){
        get_win(1);
    }else{
        get_win(0);
    }
}

?>
    <div class="frame_box" id="hx-server">
	    <h3>服务器主要参数</h3>
		<table border="0" cellspacing="1" cellpadding="3" class="table1">
        <tr>
          <th width="90">主机名</th>
          <td width="210"><?php echo php_uname('n'); ?></td>
          <th width="90">操作系统</th>
          <td width="210"><?php echo $sys['os']; ?></td>
        </tr>
        <tr>
          <th>CPU信息</th>
          <td><?php echo $cpu['model']?></td>
          <th>CPU二级缓存</th>
          <td><?php echo $cpu['cache']?></td>
        </tr>
        <tr>
          <th>内存信息</th>
          <td colspan="3">
<?php echo $mem['info'];?>
          </td>
        </tr>
        <tr>
          <th>WEB服务器</th>
          <td><?php echo $s['SERVER_SOFTWARE']; ?></td>
          <th>服务器域名</th>
          <td><?php echo $s['SERVER_NAME']?></td>
        </tr>
        <tr>
          <th>服务器IP</th>
          <td><?php echo isset($s['SERVER_ADDR']) ? $s['SERVER_ADDR'] : '获取失败'; ?></td>
          <th>服务器端口</th>
          <td><?php echo $s['SERVER_PORT']; ?></td>
        </tr>

        <tr>
          <th>管理员</th>
          <td><?php echo isset($s['SERVER_ADMIN']) ? $s['SERVER_ADMIN'] : '没填'; ?></td>
          <th>服务器时间</th>
          <td><?php echo date("Y-m-d H:i:s")?></td>
        </tr>
        <tr>
            <th>根目录</th>
            <td colspan="3"><?php echo $s['DOCUMENT_ROOT']; ?></td>
        </tr>
		<?php if (function_exists('sys_getloadavg')){ ?>
		<tr>
		    <th>系统负载</th>
		    <td colspan="3"><?php $load = sys_getloadavg();
		        echo $load[0] .','.$load[1].','.$load[2].'　三个数值分别为 1分钟、5分钟、15分钟前到现在的任务队列的平均值。';?></td></tr>
		<?php } ?>
		<?php if (function_exists('apache_get_modules')){ ?>
		<tr>
			<th>Apache模块:</th>
			<td colspan="3"><?php echo implode(', ', (array) apache_get_modules()); ?></td>
		</tr>
		<?php } ?>
		<tr>
			<th>磁盘信息</th>
			<td colspan="3">当前磁盘分区下 可用空间：<?php echo size_format(disk_free_space($dirname),2); ?> 总空间：<?php echo size_format(disk_total_space($dirname),2); ?></td>
		</tr>
		</table>
	</div>
<?php }

if($flag && $ac == 'show_var'){
    $co = $_GET['co'];
    if($co == 'server'){
        $title = '$_SERVER变量';
        $s = $_SERVER;
    }elseif($co == 'env'){
        $title = '$_ENV变量';
        $s = $_ENV;
    }elseif($co == 'cookie'){
        $title = '$_COOKIE变量';
        $s = $_COOKIE;
    }else{
        return;
    }
    ?>
    <div class="frame_box" id="hx-server">
		<h3><?php echo $title; ?></h3>
        <table border="0" cellpadding="2" cellspacing="1" class="table1">
        <tr>
            <td width="100">变量名</td>
            <td width="500">值</td>
        </tr>
		<?php
        foreach($s as $key => $value){
            echo '<tr><th>'.$key.'</th><td>'.$value.'</td></tr>';
		}?>
        </table>
    </div>
<?php
}
if($ac == '' || $ac == 'hx-php'){?>
    <div class="frame_box" id="hx-php">
        <h3>PHP主要参数</h3>
		<table border="0" cellspacing="1" cellpadding="3" class="table1">
			<tr>
				<th width="90">PHP版本</th>
				<td width="210"><?php echo PHP_VERSION; ?></td>
				<th width="90">PHP运行方式</th>
				<td width="210"><?php echo php_sapi_name(); ?></td>
			</tr>
			<tr>
			    <th>Zend引擎</th>
				<td><?php echo zend_version(); ?></td>
				<th>ZEND编译运行</th>
				<td><?php echo (ini_get("zend_optimizer.optimization_level")||ini_get("zend_extension_manager.optimizer_ts")||ini_get("zend_extension_ts")) ?"支持":"不支持"?></td>
			</tr>
			<tr>
				<th>运行于安全模式</th>
				<td><?php echo get_ini('safe_mode'); ?></td>
				<th>&lt;? ?&gt;支持</th>
				<td><?php echo get_ini('short_open_tag'); ?></td>
			</tr>
			<tr>
				<th>PHP内存限制</th>
				<td><?php echo ini_get('memory_limit'); ?></td>

				<th>内存使用</th>
				<td><?php if( function_exists('memory_get_usage') ){
				        echo size_format(memory_get_usage(), 2);
				    }else{
				        echo '暂不支持';
				    }?></td>
			</tr>
			<tr>
				<th>已加截的模块</th>
				<td colspan="3" width="510"><?php echo implode(', ', get_loaded_extensions()); ?></td>
			</tr>
			<tr>
				<th>动态加载模块</th>
				<td><?php echo ini_get("enable_dl") ? "允许":"不允许"?></td>
				<th>PHP包含路径：</th>
				<td><?php echo get_include_path(); ?></td>
			</tr>
			<tr>
				<th>最多POST：</th>
				<td><?php echo ini_get('post_max_size'); ?></td>
				<th>最大可上传：</th>
				<td><?php echo ini_get('upload_max_filesize'); ?></td>
			</tr>
			<tr>
				<th>被禁用的函数</th>
				<td><?php echo $dis_fun ? $dis_fun : '无';?></td>
				<th>脚本超时时间</th>
				<td><?php echo ini_get('max_execution_time'); ?></td>
			</tr>

		</table>
	</div>
    <div class="frame_box">
        <h3>PHP安全选项</h3>
		<table border="0" cellspacing="1" cellpadding="3" class="table1">
			<tr>
				<th width="90">显示错误信息</th>
				<td width="510">display_errors <?php if(ini_get('display_errors')){
				        echo 'On 开启<div class="msgWarn">生产环境建议关闭。</div>';
				    }else{
				        echo 'Off 已关闭。';
				    } ?></td>
			</tr>
			<tr>
				<th>自动全局变量</th>
				<td>register_globals <?php if(ini_get('register_globals')){
				        echo 'On 开启。<div class="msgWarn">强烈建议关闭！</div>';
				    }else{
				        echo 'Off 已关闭。';
				    } ?></td>
			</tr>
			<tr>
				<th>魔术引号</th>
				<td>magic_quotes_gpc <?php if(get_magic_quotes_gpc()){
				        echo 'On 开启。<div class="msgWarn">出于可移植性、性能等考虑建议关闭。</div>';
				    }else{
				        echo 'Off 已关闭。<div class="msgWarn">如果是插入数据库的数据则需要通过程序进行转义（如 addslashes()）。</div>';
				    } ?></td>
			</tr>
			<tr>
				<th>允许远程调用</th>
				<td>allow_url_fopen<?php if(ini_get('allow_url_fopen')){
				        echo 'On 开启。<div class="msgWarn">可以包含、读取远程文件，可能会有些风险。</div>';
				    }else{
				        echo 'Off 已关闭。<div class="msgWarn">不可以读取远程文件。</div>';
				    } ?></td>
			</tr>
			<?php if ( !function_exists('version_compare') || version_compare( phpversion(), '6', '>' )){?>
			<tr>
				<th>允许远程被调用</th>
				<td>allow_url_include <?php if(ini_get('allow_url_include')){
				        echo 'On 开启。<div class="msgWarn">强烈建议关闭！</div>';
				    }else{
				        echo 'Off 已关闭';
				    } ?></td>
			</tr>
			<?php }?>
			<tr>
				<th>是否目录限制</th>
				<td>open_basedir <?php
				    $open_basedir = (ini_get('open_basedir') && trim(ini_get('open_basedir')) != '') ? 1 : 0;
				    if($open_basedir){
				        echo '已设置为'.ini_get('open_basedir');
				    }else{
				        echo '没有设置<div class="msgWarn">可以设置为网站根目录，以提高安全性</div>';
				    } ?></td>
			</tr>
		</table>
    </div>

<?php
}

if($ac == 'hx-test'){
    $t1 = microtime_float();
	//开始计算50万次加法所需时间
	for($i=1;$i<500000;$i++){
	    $tmp_value = 1 + 1;
	}
    $t2 = microtime_float();
    $runtime1=number_format(($t2-$t1)*1000,2);
    //开始计算20万次开方所需时间
    $t1 = microtime_float();
	for($i=1;$i<200000;$i++){
	    $tmp_value = pow(2, 2);
	}
    $t2 = microtime_float();
    $runtime2=number_format(($t2-$t1)*1000,2);
    //开始计算I/O读写时间
    function io_test(){
        $t1 = microtime_float();
        for($i=0;$i<30;$i++){
            $filename = 'Hx_Test_'.$i.'.txt';
            if (!$handle = @fopen($filename, 'a')) {
                return 0;
            }
            if (@fwrite($handle, "Create:It's a hxtest file.") === FALSE) {
                return 0;
            }
            fclose($handle);
            $handle = fopen($filename, 'w');
            fwrite($handle, "Appending:It's a hxtest file.");
            fclose($handle);
            unlink($filename);
        }
        $t2 = microtime_float();
        $runtime3=number_format(($t2-$t1)*1000,2);
        return $runtime3;
    }
    $runtime3 = io_test();
    if($runtime3 == 0){
        $runtime3 = '当前目录没有权限创建文件，无法测试！';
    }else{
        $runtime3 = $runtime3.' 毫秒';
    }
?>
    <div class="frame_box" id="hx-test">
        <h3>服务器性能测试</h3>
        <table border="0" cellspacing="1" cellpadding="3" class="table1">
        <tr>
          <th colspan="4">· 整数运算：让服务器执行50万次加法(1+1)，记录其所使用的时间。
            <br />· 浮点运算：让服务器执行20万次开方(2<sup>2</sup>)，记录其所使用的时间。
            <br />· I/O 读写：重复创建、写入、追加和删除文本文件30次，记录其所使用的时间。
            <br />建议您多测几次，取平均值，这样会比较接近真实值。
          </th>
        </tr>
        <tr class="hx_tr3">
          <td width="360">可 供 参 考 的 服 务 器 列 表</td>
          <td width="80">整数运算</td>
          <td width="80">浮点运算</td>
          <td width="80">I/O读写</td>
        </tr>
        <tr>
          <td class="hx_tr1"><a href="http://www.9enjoy.com/post/277/" target="_blank">ITlearner08年配的电脑</a> (CPU:酷睿2 E4500 2.2G 内存:2G)</td>
          <td>65.37 毫秒</td>
          <td>129.49 毫秒</td>
          <td>51.95 毫秒</td>
        </tr>
        <tr>
          <td class="hx_tr1"><a href="http://www.itlearner.com" target="_blank">ITlearner</a>05年的老服务器 (CPU:P4 3.0G(1M) 内存:1.5G)</td>
          <td>82.90 毫秒</td>
          <td>152.92 毫秒</td>
          <td>62.95 毫秒</td>
        </tr>
        <tr>
          <td class="hx_tr1"><a href="http://www.9enjoy.com/host/rashost.html" target="_blank">瑞豪开源提供的VPS(128M)</a> [2010/01/21]</td>
          <td>46.13 毫秒</td>
          <td>85.18 毫秒</td>
          <td>2.15 毫秒</td>
        </tr>
        <tr>
          <th class="hx_tr1"><a href="http://www.diantai8.com" target="_blank">Godaddy提供虚拟主机(DELUXE PLAN)</a> [2010/01/21]</th>
          <td>70.67 毫秒</td>
          <td>91.17 毫秒</td>
          <td>227.97 毫秒</td>
        </tr>
        <tr>
          <td class="hx_tr1"><span class="font_3">您正在使用的这台服务器</span>&nbsp; <input name="button" type="button" class="btn_c"  onclick="document.location.href='<?php echo $script_name?>?ac=hx-test'" value="重新测试" />
          </td>
          <td><span class="font_3"><?php echo $runtime1;?> 毫秒</span></td>
          <td><span class="font_3"><?php echo $runtime2;?> 毫秒</span></td>
          <td><span class="font_3"><?php echo $runtime3;?></span></td>
        </tr>
        </table>
	</div>
<?php
}

    $runtime= microtime_float()-$startime;
    if($runtime > 0.5){
        $runtime = number_format($runtime,2) . ' 秒';
    }else{
        $runtime = number_format($runtime * 1000,2) . ' 毫秒';
    }
?>
<div id="hx-footer">
    <p><a href="http://www.itlearner.com" target="_blank">IT学习者</a> | <a href="http://www.9enjoy.com" target="_blank">作者Blog</a> | <a href="http://www.9enjoy.com/phpcheck/" target="_blank">下载最新版</a><br />页面执行时间：约 <?php echo $runtime?>&nbsp;&nbsp;<a href="http://www.9enjoy.com/phpcheck/" target="_blank">PhpCheck <?php echo $ver?></a></p>
</div>
</body>
</html>