原作者PHP源代码350KB,发现代码里面有很多没用的东西,索性重新写了个“精简版”。

代码基于handsome主题修改,其他主题如需使用请自行修改代码适配。精简后的PHP代码仅支持Linux系统,在Centos7.6和7.9上测试通过,其他Linux系统未进行测试,兼容性未知。

功能演示

功能演示

文件修改 headnav.php

文件路径:usr/themes/handsome/component/headnav.php

在此处:

    <!-- statitic info-->
    <?php
    if (@Utils::getExpertValue("show_static",true) !== false): ?>
    <ul class="nav navbar-nav hidden-sm">

        <!-- 在此追加代码 -->

        <li class="dropdown pos-stc">

追加内容(此处为追加后的代码):

    <!-- statitic info-->
    <?php
    if (@Utils::getExpertValue("show_static",true) !== false): ?>
    <ul class="nav navbar-nav hidden-sm">

        <!-- 这里开始是新追加的内容 -->
        <li class="dropdown pos-stc" id="StateDataPos">
            <a id="StateData" href="#" data-toggle="dropdown" class="dropdown-toggle feathericons dropdown-toggle">
              <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-activity"><polyline points="22 12 18 12 15 21 9 3 6 12 2 12"></polyline></svg>
              <span class="caret"></span>
            </a>
            <div class="dropdown-menu wrapper w-full bg-white">
                <div class="row">
                    <div class="col-sm-4 b-l b-light">
                        <div class="m-t-xs m-b-xs font-bold">运行状态</div>
                        <div class="">
                            <span class="pull-right text-danger" id="cpu">
                                <i class="fa fa-spinner fa-spin" aria-hidden="true"></i>
                            </span>
                            <span>CPU占用
                                <span class="badge badge-sm bg-info">2核心</span>
                            </span>
                        </div>
                        <div class="progress progress-xs m-t-sm bg-default">
                            <div id="cpu_css" class="progress-bar bg-danger" data-toggle="tooltip" style="width: 100%"></div>
                        </div>
                        <div class="">
                            <span class="pull-right text-danger" id="memory">
                                <i class="fa fa-spinner fa-spin" aria-hidden="true"></i>
                            </span>
                            <span>占用内存
                                <span class="badge badge-sm bg-dark" id="memory_data">
                                    <i class="fa fa-spinner fa-spin" aria-hidden="true"></i>
                                </span>
                            </span>
                        </div>
                        <div class="progress progress-xs m-t-sm bg-default">
                            <div id="memory_css" class="progress-bar bg-danger" data-toggle="tooltip" style="width: 100%"></div>
                        </div>
                        <div class="">
                            <span class="pull-right text-danger" id="disk">
                                <i class="fa fa-spinner fa-spin" aria-hidden="true"></i>
                            </span>
                            <span>磁盘占用
                                <span class="badge badge-sm bg-dark" id="disk_data">
                                    <i class="fa fa-spinner fa-spin" aria-hidden="true"></i>
                                </span>
                            </span>
                        </div>
                        <div class="progress progress-xs m-t-sm bg-default">
                            <div id="disk_css" class="progress-bar bg-danger" data-toggle="tooltip" style="width: 100%"></div>
                        </div>
                        <div class="">
                            <span class="pull-right text-danger" id="memCached">
                                <i class="fa fa-spinner fa-spin" aria-hidden="true"></i>
                            </span>
                            <span>内存缓存
                                <span class="badge badge-sm bg-dark" id="memCached_data">
                                    <i class="fa fa-spinner fa-spin" aria-hidden="true"></i>
                                </span>
                            </span>
                        </div>
                        <div class="progress progress-xs m-t-sm bg-default">
                            <div id="memCached_css" class="progress-bar bg-danger" data-toggle="tooltip" style="width: 100%"></div>
                        </div>
                        <div class="">
                            <span class="pull-right text-danger" id="memBuffers">
                                <i class="fa fa-spinner fa-spin" aria-hidden="true"></i>
                            </span>
                            <span>内存缓冲
                                <span class="badge badge-sm bg-dark" id="memBuffers_data">
                                    <i class="fa fa-spinner fa-spin" aria-hidden="true"></i>
                                </span>
                            </span>
                        </div>
                        <div class="progress progress-xs m-t-sm bg-default">
                            <div id="memBuffers_css" class="progress-bar bg-danger" data-toggle="tooltip" style="width: 100%"></div>
                        </div>
                        <div class="">
                            <span class="pull-right text-danger" id="state_s">
                                <i class="fa fa-spinner fa-spin" aria-hidden="true"></i>
                            </span>
                            <span>系统负载
                                <span id="state">
                                    <span class="badge badge-sm bg-dark">
                                        <i class="fa fa-spinner fa-spin" aria-hidden="true"></i>
                                    </span>
                                </span>
                            </span>
                        </div>
                        <div class="progress progress-xs m-t-sm bg-default">
                            <div id="state_css" class="progress-bar bg-danger" data-toggle="tooltip" style="width: 100%"></div>
                        </div>
                    </div>
                    <div class="col-sm-4 b-l b-light visible-lg visible-md">
                        <div class="m-t-xs m-b-xs font-bold">网络状态</div>
                        <div class="">
                            <span class="pull-right text-default" id="io">
                                <i class="fa fa-spinner fa-spin" aria-hidden="true"></i>
                            </span>
                            <span>IO</span>
                        </div>
                        <br/>
                        <div class="">
                            <span class="pull-right text-default" id="io1">
                                <i class="fa fa-spinner fa-spin" aria-hidden="true"></i>
                            </span>
                            <span>实时IO</span>
                        </div>
                        <br/>
                        <div class="">
                            <span class="pull-right text-default" id="eth">
                                <i class="fa fa-spinner fa-spin" aria-hidden="true"></i>
                            </span>
                            <span>网络</span>
                        </div>
                        <br/>
                        <div class="">
                            <span class="pull-right text-default" id="eth1">
                                <i class="fa fa-spinner fa-spin" aria-hidden="true"></i>
                            </span>
                            <span>实时网络</span>
                        </div>
                        <br/>
                        <div class="">
                            <span class="pull-right text-default" id="time">
                                <i class="fa fa-spinner fa-spin" aria-hidden="true"></i>
                            </span>
                            <span>服务器时间</span>
                        </div>
                        <br/>
                        <div class="">
                            <span class="pull-right text-default">
                                <span class="badge badge-sm bg-dark"><?php echo $_SERVER['SERVER_SOFTWARE']; ?></span></span>
                            <span>WEB服务器</span>
                        </div>
                        <br/>
                        <div class="">
                            <span class="pull-right text-default">
                                <span class="badge badge-sm bg-dark"><?php echo $_SERVER['SERVER_PROTOCOL']; ?></span>
                            </span>
                            <span>通信协议</span>
                        </div>
                        <br/>
                        <div class="">
                            <span class="pull-right text-default">
                                <span class="badge badge-sm bg-dark"><?php echo PHP_VERSION;?></span>
                            </span>
                            <span>PHP版本</span>
                        </div>
                        <br/>
                    </div>
                    <div class="col-sm-4 b-l b-light visible-lg visible-md">
                        <div class="m-t-xs m-b-sm font-bold">访客信息</div>
                        <div class="">
                            <span class="pull-right text-default" id="u_time">
                                <i class="fa fa-spinner fa-spin" aria-hidden="true"></i>
                            </span>
                            <span>持续运行</span>
                        </div>
                        <br/>
                        <div class="">
                            <span class="pull-right text-default" id="ip">
                                <i class="fa fa-spinner fa-spin" aria-hidden="true"></i>
                            </span>
                            <span>您的IP</span>
                        </div>
                        <br/>
                        <div class="">
                            <span class="pull-right text-default" id="address">
                                <i class="fa fa-spinner fa-spin" aria-hidden="true"></i>
                            </span>
                            <span>网络地址</span>
                        </div>
                        <br/>
                        <div class="">
                            <span class="pull-right text-default" id="b">
                                <i class="fa fa-spinner fa-spin" aria-hidden="true"></i>
                            </span>
                            <span>浏览器信息</span>
                        </div>
                        <br/>
                        <div class="">
                            <span class="pull-right text-default" id="sys">
                                <i class="fa fa-spinner fa-spin" aria-hidden="true"></i>
                            </span>
                            <span>您的设备</span>
                        </div>
                        <br/>
                        <div class="">
                            <span class="pull-right text-default">
                                <span class="badge badge-sm bg-dark"><?php echo $_SERVER['REQUEST_METHOD'];?></span></span>
                            <span>请求方法</span>
                        </div>
                        <br/>
                        <div class="">
                            <span class="pull-right text-default">
                                <span class="badge badge-sm bg-dark"><?php echo $_SERVER['HTTP_ACCEPT_LANGUAGE'];?></span></span>
                            <span>服务语言</span>
                        </div>
                        <br/>
                        <div class="">
                            <span class="pull-right text-default" id="sys_times">
                                <i class="fa fa-spinner fa-spin" aria-hidden="true"></i>
                            </span>
                            <span>您的设备时间</span>
                        </div>
                    </div>
                </div>
            </div>
        </li>
        <!-- 新追加的内容到此结束 -->

        <li class="dropdown pos-stc">

文件修改 footer.php

文件路径:usr/themes/handsome/component/footer.php

在此处:

<?php $this->options->bottomHtml(); ?>

   <!-- 在此追加代码 -->

</body>
</html><!--html end-->

追加内容(此处为追加后的代码):


<?php $this->options->bottomHtml(); ?>

<!-- 这里开始是新追加的内容 -->
<script>
var stateUrl = '/serverInfo.php';
var se_rx;
var se_tx;
var si_rx;
var si_tx;
function returnFloat(value){
    return value.toFixed(2)+'%';
}
function floats(value){
    return value.toFixed(2);
}
function getPercent(curNum, totalNum, isHasPercentStr) {
    curNum = parseFloat(curNum);
    totalNum = parseFloat(totalNum);

    if (isNaN(curNum) || isNaN(totalNum)) {
        return 'Error';
    }

    return isHasPercentStr ?
        totalNum <= 0 ? '0%' : (Math.round(curNum / totalNum * 10000) / 100.00 + '%') :
        totalNum <= 0 ? 0 : (Math.round(curNum / totalNum * 10000) / 100.00  + '%');
}
function getPercents(curNum, totalNum, isHasPercentStr) {
    curNum = parseFloat(curNum);
    totalNum = parseFloat(totalNum);

    if (isNaN(curNum) || isNaN(totalNum)) {
        return 'Error';
    }

    return isHasPercentStr ?
        totalNum <= 0 ? '0%' : (Math.round(curNum / totalNum * 10000) / 100.00) :
        totalNum <= 0 ? 0 : (Math.round(curNum / totalNum * 10000) / 100.00);
}
function setSize(value,d){
    switch (d) {
        case 'bit':
            return bit = value*8;
            break;
        case 'bytes':
            return value;
            break;
        case 'kb':
            return value/1024;
            break;
        case 'mb':
            return value/1024/1024;
            break;
        case 'gb':
            return value/1024/1024/1024;
            break;
        case 'tb':
            return value/1024/1024/1024/1024;
            break;
    }
}
function ForDight(Dight){ 
    if (Dight < 0){
        var Last = 0+"B/s";
    }else if (Dight < 1024){
        var Last = setSize(Dight,'bytes').toFixed(0)+"B/s";
    }else if (Dight < 1048576){
        var Last = floats(setSize(Dight,'kb'))+"K/s";
    }else{
        var Last = floats(setSize(Dight,'mb'))+"MB/s";
    }
    return Last; 
}
function state(){
    $.ajax({
        url: stateUrl,
        type: 'get',
        dataType: 'json',
        data: {
            action:'fetch',
        },
        beforeSend:function(){
            
        },
        complete:function(){
            
        },
        error: function() {
        }, 
        success: function (data) {
            var cpu = data.serverStatus.cpuUsage['user']+data.serverStatus.cpuUsage['nice']+data.serverStatus.cpuUsage['sys'];
            $("#cpu").html(returnFloat(cpu));
            $("#cpu_css").css("width",returnFloat(cpu));
            if(cpu<70){
                $("#cpu_css").removeClass();
                $("#cpu_css").addClass("progress-bar bg-success");
                $("#cpu").removeClass();
                $("#cpu").addClass("pull-right text-success");
            }
            if(cpu>=70){
                $("#cpu_css").removeClass();
                $("#cpu_css").addClass("progress-bar bg-warning");
                $("#cpu").removeClass();
                $("#cpu").addClass("pull-right text-warning");
            }
            if(cpu>=90){
                $("#cpu_css").removeClass();
                $("#cpu_css").addClass("progress-bar bg-danger");
                $("#cpu").removeClass();
                $("#cpu").addClass("pull-right text-danger");
            }
            
            var memory_value = data.serverStatus.memRealUsage['value'];
            var memory_max = data.serverStatus.memRealUsage['max'];
            $("#memory").html(getPercent(memory_value,memory_max,memory_value));
            window.RemData = getPercents(memory_value,memory_max,memory_value);
            $("#memory_css").css("width",getPercent(memory_value,memory_max,memory_value));
            var me = getPercents(memory_value,memory_max,memory_value);
            if(me<70){
                $("#memory_css").removeClass();
                $("#memory_css").addClass("progress-bar bg-success");
                $("#memory").removeClass();
                $("#memory").addClass("pull-right text-success");
            }
            if(me>=70){
                $("#memory_css").removeClass();
                $("#memory_css").addClass("progress-bar bg-warning");
                $("#memory").removeClass();
                $("#memory").addClass("pull-right text-warning");
            }
            if(me>=90){
                $("#memory_css").removeClass();
                $("#memory_css").addClass("progress-bar bg-danger");
                $("#memory").removeClass();
                $("#memory").addClass("pull-right text-danger");
            }
            if(floats(setSize(memory_value,'mb'))>1024){
                var memory_data_value = floats(setSize(memory_value,'gb'))+"GB";
            } else{
                var memory_data_value = floats(setSize(memory_value,'mb'))+"MB";
            }
            if(floats(setSize(memory_max,'mb'))>1024){
                var memory_data_max = floats(setSize(memory_max,'gb'))+"GB";
            } else{
                var memory_data_max = floats(setSize(memory_max,'mb'))+"MB";
            }
            $("#memory_data").html(memory_data_value+" / "+memory_data_max);
            
            var disk_value = data.serverInfo.diskUsage['value'];
            var disk_max = data.serverInfo.diskUsage['max'];
            $("#disk").html(getPercent(disk_value,disk_max,disk_value));
            $("#disk_css").css("width",getPercent(disk_value,disk_max,disk_value));
            var dk = getPercents(disk_value,disk_max,disk_value);
            if(dk<70){
                $("#disk_css").removeClass();
                $("#disk_css").addClass("progress-bar bg-success");
                $("#disk").removeClass();
                $("#disk").addClass("pull-right text-success");
            }
            if(dk>=70){
                $("#disk_css").removeClass();
                $("#disk_css").addClass("progress-bar bg-warning");
                $("#disk").removeClass();
                $("#disk").addClass("pull-right text-warning");
            }
            if(dk>=90){
                $("#disk_css").removeClass();
                $("#disk_css").addClass("progress-bar bg-danger");
                $("#disk").removeClass();
                $("#disk").addClass("pull-right text-danger");
            }
            if(floats(setSize(disk_value,'mb'))>1024){
                var disk_data_value = floats(setSize(disk_value,'gb'))+"GB";
            } else{
                var disk_data_value = floats(setSize(disk_value,'mb'))+"MB";
            }
            if(floats(setSize(disk_max,'mb'))>1024){
                var disk_data_max = floats(setSize(disk_max,'gb'))+"GB";
            } else{
                var disk_data_max = floats(setSize(disk_max,'mb'))+"MB";
            }
            $("#disk_data").html(disk_data_value+" / "+disk_data_max);
            
            var memCached_value = data.serverStatus.memCached['value'];
            var memCached_max = data.serverStatus.memCached['max'];
            $("#memCached").html(getPercent(memCached_value,memCached_max,memCached_value));
            $("#memCached_css").css("width",getPercent(memCached_value,memCached_max,memCached_value));
            var mem = getPercents(memCached_value,memCached_max,memCached_value);
            if(mem<70){
                $("#memCached_css").removeClass();
                $("#memCached_css").addClass("progress-bar bg-success");
                $("#memCached").removeClass();
                $("#memCached").addClass("pull-right text-success");
            }
            if(mem>=70){
                $("#memCached_css").removeClass();
                $("#memCached_css").addClass("progress-bar bg-warning");
                $("#memCached").removeClass();
                $("#memCached").addClass("pull-right text-warning");
            }
            if(mem>=90){
                $("#memCached_css").removeClass();
                $("#memCached_css").addClass("progress-bar bg-danger");
                $("#memCached").removeClass();
                $("#memCached").addClass("pull-right text-danger");
            }
            if(floats(setSize(memCached_value,'mb'))>1024){
                var memCached_data_value = floats(setSize(memCached_value,'gb'))+"GB";
            } else{
                var memCached_data_value = floats(setSize(memCached_value,'mb'))+"MB";
            }
            if(floats(setSize(memCached_max,'mb'))>1024){
                var memCached_data_max = floats(setSize(memCached_max,'gb'))+"GB";
            } else{
                var memCached_data_max = floats(setSize(memCached_max,'mb'))+"MB";
            }
            $("#memCached_data").html(memCached_data_value+" / "+memCached_data_max);
            
            var memBuffers_value = data.serverStatus.memBuffers['value'];
            var memBuffers_max = data.serverStatus.memBuffers['max'];
            $("#memBuffers").html(getPercent(memBuffers_value,memBuffers_max,memBuffers_value));
            $("#memBuffers_css").css("width",getPercent(memBuffers_value,memBuffers_max,memBuffers_value));
            var memB = getPercents(memCached_value,memCached_max,memCached_value);
            if(memB<70){
                $("#memBuffers_css").removeClass();
                $("#memBuffers_css").addClass("progress-bar bg-success");
                $("#memBuffers").removeClass();
                $("#memBuffers").addClass("pull-right text-success");
            }
            if(memB>=70){
                $("#memBuffers_css").removeClass();
                $("#memBuffers_css").addClass("progress-bar bg-warning");
                $("#memBuffers").removeClass();
                $("#memBuffers").addClass("pull-right text-warning");
            }
            if(memB>=90){
                $("#memBuffers_css").removeClass();
                $("#memBuffers_css").addClass("progress-bar bg-danger");
                $("#memBuffers").removeClass();
                $("#memBuffers").addClass("pull-right text-danger");
            }
            if(floats(setSize(memBuffers_value,'mb'))>1024){
                var memBuffers_data_value = floats(setSize(memBuffers_value,'gb'))+"GB";
            } else{
                var memBuffers_data_value = floats(setSize(memBuffers_value,'mb'))+"MB";
            }
            if(floats(setSize(memBuffers_max,'mb'))>1024){
                var memBuffers_data_max = floats(setSize(memBuffers_max,'gb'))+"GB";
            } else{
                var memBuffers_data_max = floats(setSize(memBuffers_max,'mb'))+"MB";
            }
            $("#memBuffers_data").html(memBuffers_data_value+" / "+memBuffers_data_max);
            
            var state = "";
            for(var i = 0; i < data.serverStatus.sysLoad.length ; i++){
                state += '<span class="badge badge-sm bg-dark">'+data.serverStatus.sysLoad[i]+'</span>&nbsp;'
            }
            $("#state").html(state);
            var state_s = getPercent(data.serverStatus.sysLoad[0],2,data.serverStatus.sysLoad[0]);
            $("#state_css").css("width",state_s);
            $("#state_s").html(state_s);
            var sta = getPercents(data.serverStatus.sysLoad[0],2,data.serverStatus.sysLoad[0]);
            if(sta<70){
                $("#state_css").removeClass();
                $("#state_css").addClass("progress-bar bg-success");
                $("#state_s").removeClass();
                $("#state_s").addClass("pull-right text-success");
            }
            if(sta>=70){
                $("#state_css").removeClass();
                $("#state_css").addClass("progress-bar bg-warning");
                $("#state_s").removeClass();
                $("#state_s").addClass("pull-right text-warning");
            }
            if(sta>=90){
                $("#state_css").removeClass();
                $("#state_css").addClass("progress-bar bg-danger");
                $("#state_s").removeClass();
                $("#state_s").addClass("pull-right text-danger");
            }
            
            $("#time").html('<span class="badge badge-sm bg-dark">'+data.serverInfo.serverTime+'</span>');
            
            $("#u_time").html('<span class="badge badge-sm bg-dark">'+data.serverInfo.serverUptime["days"]+' 天'+data.serverInfo.serverUptime["hours"]+' 时 '+data.serverInfo.serverUptime["mins"]+' 分'+data.serverInfo.serverUptime["secs"]+' 秒</span>');
            
            if(floats(setSize(data.networkStats.networks.eth0.tx,'mb'))>1024){
                var aaa_tx = floats(setSize(data.networkStats.networks.eth0.tx,'gb'))+"GB";
            } else{
                var aaa_tx = floats(setSize(data.networkStats.networks.eth0.tx,'mb'))+"MB";
            }
            if(floats(setSize(data.networkStats.networks.eth0.rx,'mb'))>1024){
                var aaa_rx = floats(setSize(data.networkStats.networks.eth0.rx,'gb'))+"GB";
            } else{
                var aaa_rx = floats(setSize(data.networkStats.networks.eth0.rx,'mb'))+"MB";
            }
        
            $("#eth").html('<span class="badge badge-sm bg-dark"><i class="glyphicon glyphicon-upload" aria-hidden="true"></i>&nbsp;'+aaa_tx+'</span>&nbsp;'+
            '<span class="badge badge-sm bg-dark"><i class="glyphicon glyphicon-download" aria-hidden="true"></i>&nbsp;'+aaa_rx+'</span>');
            $("#eth1").html('<span class="badge badge-sm bg-dark"><i class="glyphicon glyphicon-cloud-upload" aria-hidden="true"></i>&nbsp;'+ForDight(data.networkStats.networks.eth0.tx-se_tx,3)+'</span>&nbsp;'+
            '<span class="badge badge-sm bg-dark"><i class="glyphicon glyphicon-cloud-download" aria-hidden="true"></i>&nbsp;'+ForDight(data.networkStats.networks.eth0.rx-se_rx,3)+'</span>');
            se_tx = data.networkStats.networks.eth0.tx;
            se_rx = data.networkStats.networks.eth0.rx;
            if(floats(setSize(data.networkStats.networks.lo.tx,'mb'))>1024){
                var lo_tx = floats(setSize(data.networkStats.networks.lo.tx,'gb'))+"GB";
            } else{
                var lo_tx = floats(setSize(data.networkStats.networks.lo.tx,'mb'))+"MB";
            }
            if(floats(setSize(data.networkStats.networks.lo.rx,'mb'))>1024){
                var lo_rx = floats(setSize(data.networkStats.networks.lo.rx,'gb'))+"GB";
            } else{
                var lo_rx = floats(setSize(data.networkStats.networks.lo.rx,'mb'))+"MB";
            }
            $("#io").html('<span class="badge badge-sm bg-success"><i class="fa fa-upload" aria-hidden="true"></i>&nbsp;'+lo_tx+'</span>&nbsp;'+
            '<span class="badge badge-sm bg-success"><i class="glyphicon glyphicon-cloud-download" aria-hidden="true"></i>&nbsp;'+lo_rx+'</span>');
            $("#io1").html('<span class="badge badge-sm bg-dark"><i class="glyphicon glyphicon-cloud-upload" aria-hidden="true"></i>&nbsp;'+ForDight(data.networkStats.networks.lo.tx-si_tx,3)+'</span>&nbsp;'+
            '<span class="badge badge-sm bg-dark"><i class="glyphicon glyphicon-cloud-download" aria-hidden="true"></i>&nbsp;'+ForDight(data.networkStats.networks.lo.rx-si_rx,3)+'</span>');
            si_tx = data.networkStats.networks.lo.tx;
            si_rx = data.networkStats.networks.lo.rx;
        }
    });
}
function getNowFormatDate(){
    var date = new Date();
    var seperator1 = "-";
    var seperator2 = ":";
    var month = date.getMonth() + 1;
    var strDate = date.getDate();
    if (month >= 1 && month <= 9) {
      month = "0" + month;
    }
    if (strDate >= 0 && strDate <= 9) {
      strDate = "0" + strDate;
    }
    var currentdate = date.getFullYear() + seperator1 + month + seperator1 + strDate
          + " " + date.getHours() + seperator2 + date.getMinutes()
          + seperator2 + date.getSeconds();
    return currentdate;
}
function UserInfo(){
    $.ajax({
        type : "get",
        url : "https://api.qqij.cn/api/UserInfo/",
        async : true,
        beforeSend : function(){
            
        },
        complete : function(){
            
        },
        error : function(){
            UserInfo();
        },
        success : function(data){
            if(data!=null){
                if(data.data['location']==null){
                    UserInfo();
                }else{
                    $("#ip").html('<span class="badge badge-sm bg-dark">'+data.data['ip']+'</span>');
                    $("#address").html('<span class="badge badge-sm bg-dark">'+data.data['location']+'</span>');
                    $("#b").html('<span class="badge badge-sm bg-dark">'+data.data['browser']+'</span>');
                    $("#sys").html('<span class="badge badge-sm bg-dark">'+data.data['os']+'</span>');
                }
            }
        },
    });
};
$('#StateData').click(function(){
    clearInterval(window.getnet);
    clearInterval(window.info);
    window.getnet = setInterval(function(){
        if($('#StateDataPos').is('.open')){
            state();
            $("#sys_times").html('<span class="badge badge-sm bg-dark">'+getNowFormatDate()+'</span>');
        }
    },1000);
    UserInfo();
});
</script>
<!-- 新追加的内容到此结束 -->

</body>
</html><!--html end-->

新建文件 serverInfo.php

上述修改完毕之后,在网站的根目录新建 serverInfo.php 文件

文件内容如下:

<?php  
    /**
     * 获取当前Unix时间戳
     * */
    $unixTimestamp = time();
    /**
     * 获取服务器总的运行时长
     * */
    $serverUptime =  getUpTime();
    /**
     * 获取服务器负载 以及CPU使用信息
     * */
    $serverLoad = GetLoad();
    $cpuUsage = GetCPUInfo();
    /**
     * 获取服务器内存信息
     * */
    $memoryInfo = GetMem();
    
    // 定义要输出的内容  
    $serverInfo = array(  
        'serverTime' => date('Y-m-d H:i:s', $unixTimestamp),  
        'serverUptime' => array(  
            'days' => $serverUptime['days'],  
            'hours' => $serverUptime['hours'],  
            'mins' => $serverUptime['mins'],  
            'secs' => $serverUptime['secs']  
        ),  
        'serverUtcTime' => date('Y/m/d H:i:s', $unixTimestamp),  
        'diskUsage' => array(  
            'value' => disk_total_space(__FILE__) - disk_free_space(__FILE__),  
            'max' => disk_total_space(__FILE__)  
        )
    );  

    $serverStatus = array(  
        'sysLoad' => array($serverLoad['1m'], $serverLoad['5m'], $serverLoad['15m']),  
        'cpuUsage' => array(  
            'user' => $cpuUsage['user'],  
            'nice' => $cpuUsage['nice'],  
            'sys' => $cpuUsage['sys'],  
            'idle' => $cpuUsage['idle']  
        ),  
        'memRealUsage' => array(  
            'value' => $memoryInfo['mRealUsed'],  
            'max' => $memoryInfo['mTotal']  
        ),  
        'memBuffers' => array(  
            'value' => $memoryInfo['mBuffers'],  
            'max' => $memoryInfo['mTotal']  
        ),  
        'memCached' => array(  
            'value' => $memoryInfo['mCached'],  
            'max' => $memoryInfo['mTotal']  
        ),  
        'swapUsage' => array(  
            'value' => $memoryInfo['swapUsed'],  
            'max' => $memoryInfo['swapTotal']  
        ),  
        'swapCached' => array(  
            'value' => $memoryInfo['swapCached'],  
            'max' => $memoryInfo['swapTotal']  
        )  
    ); 
    

 
    
      
    $networkStats = array(  
        'networks' => GetNetwork()
    );  
    // 将以上内容合并为一个数组  
    $output = array(  
        'serverInfo' => $serverInfo,  
        'serverStatus' => $serverStatus,  
        'networkStats' => $networkStats  
    );  
      
    // 将数组转换为JSON字符串并输出  
    echo json_encode($output);  

    /**
     * 获取系统运行时长
     *
     * @return array
     */
    function getUpTime() {  
        $uptime = (float) @file_get_contents("/proc/uptime");  
        $days = floor($uptime / 86400);  
        $hours = floor(($uptime % 86400) / 3600);  
        $minutes = floor((($uptime % 86400) % 3600) / 60);  
        $seconds = ($uptime % 3600) % 60;  
        //$time = $days.":".$hours.":".$minutes.":".$seconds;  
        return array(  
            'days' => $days,  
            'hours' => $hours,  
            'mins' => $minutes,  
            'secs' => $seconds 
        );  
    }


    /**
     * 获取系统负载
     *
     * @return array|false|string[]
     */
    function GetLoad()
    {
        if (false === ($str = file_get_contents("/proc/loadavg")))
            return [];

        $loads = explode(' ', $str);
        if ($loads)
        {
            return [
                '1m'  => $loads[0],
                '5m'  => $loads[1],
                '15m' => $loads[2],
            ];
        }

        return [];
    }
    
    function GetCPUInfo()  
    {  
        $load = sys_getloadavg();  
        $user = $load[0];  
        $nice = $load[1];  
        $sys = $load[2];  
        $idle = 100 - ($user + $nice + $sys);  
        return [  
            'user' => $user,  
            'nice' => $nice,  
            'sys' => $sys,  
            'idle' => $idle,  
        ];  
    }



    /**
     * 内存信息
     *
     * @param bool $bFormat 格式化
     *
     * @return array
     */
    function GetMem(bool $bFormat = false)
    {
        if (false === ($str = file_get_contents("/proc/meminfo")))
            return [];

        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, $mems);
        preg_match_all("/Buffers\s{0,}\:+\s{0,}([\d\.]+)/s", $str, $buffers);

        $mtotal    = $mems[1][0] * 1024;
        $mfree     = $mems[2][0] * 1024;
        $mbuffers  = $buffers[1][0] * 1024;
        $mcached   = $mems[3][0] * 1024;
        $stotal    = $mems[4][0] * 1024;
        $sfree     = $mems[5][0] * 1024;
        $mused     = $mtotal - $mfree;
        $sused     = $stotal - $sfree;
        $mrealused = $mtotal - $mfree - $mcached - $mbuffers; //真实内存使用
        $rtn['mTotal']         = !$bFormat ? $mtotal : $this->size_format($mtotal, 1);
        $rtn['mFree']          = !$bFormat ? $mfree : $this->size_format($mfree, 1);
        $rtn['mBuffers']       = !$bFormat ? $mbuffers : $this->size_format($mbuffers, 1);
        $rtn['mCached']        = !$bFormat ? $mcached : $this->size_format($mcached, 1);
        $rtn['mUsed']          = !$bFormat ? ($mtotal - $mfree) : $this->size_format($mtotal - $mfree, 1);
        $rtn['mPercent']       = (floatval($mtotal) != 0) ? round($mused / $mtotal * 100, 1) : 0;
        $rtn['mRealUsed']      = !$bFormat ? $mrealused : $this->size_format($mrealused, 1);
        $rtn['mRealFree']      = !$bFormat ? ($mtotal - $mrealused) : $this->size_format($mtotal - $mrealused, 1);//真实空闲
        $rtn['mRealPercent']   = (floatval($mtotal) != 0) ? round($mrealused / $mtotal * 100, 1) : 0;             //真实内存使用率
        $rtn['mCachedPercent'] = (floatval($mcached) != 0) ? round($mcached / $mtotal * 100, 1) : 0;              //Cached内存使用率
        $rtn['swapTotal']      = !$bFormat ? $stotal : $this->size_format($stotal, 1);
        $rtn['swapFree']       = !$bFormat ? $sfree : $this->size_format($sfree, 1);
        $rtn['swapUsed']       = !$bFormat ? $sused : $this->size_format($sused, 1);
        $rtn['swapPercent']    = (floatval($stotal) != 0) ? round($sused / $stotal * 100, 1) : 0;
        $rtn['swapCached'] = $mbuffers;
        return $rtn;
    }
    

    /**
     * 获取网络数据
     *
     * @param bool $bFormat
     *
     * @return array
     */
    function GetNetwork(bool $bFormat = false)
    {
        $rtn     = [];
        $netstat = file_get_contents('/proc/net/dev');
        if (false === $netstat)
        {
            return [];
        }

        $bufe = preg_split("/\n/", $netstat, -1, PREG_SPLIT_NO_EMPTY);
        foreach ($bufe as $buf)
        {
            if (preg_match('/:/', $buf))
            {
                list($dev_name, $stats_list) = preg_split('/:/', $buf, 2);
                $dev_name = trim($dev_name);

                $stats                        = preg_split('/\s+/', trim($stats_list));
                $rtn[$dev_name]['name']       = $dev_name;
                $rtn[$dev_name]['rx']    = !$bFormat ? $stats[0] : $this->netSize($stats[0]);
                $rtn[$dev_name]['in_packets'] = $stats[1];
                $rtn[$dev_name]['in_errors']  = $stats[2];
                $rtn[$dev_name]['in_drop']    = $stats[3];

                $rtn[$dev_name]['tx'] = !$bFormat ? $stats[8] : $this->netSize($stats[8]);
                $rtn[$dev_name]['out_packets'] = $stats[9];
                $rtn[$dev_name]['out_errors']  = $stats[10];
                $rtn[$dev_name]['out_drop']    = $stats[11];
            }
        }

        return $rtn;
    }

至此,博客已经成功添加添加服务器状态栏,可以刷新后点击状态栏图标查看。

宝塔面板报错

若使用的是宝塔面板环境,请修改网站根目录中的.user.ini文件

open_basedir=/www/wwwroot/zai.ink/:/tmp/

追加代码::/proc/后:

open_basedir=/www/wwwroot/zai.ink/:/tmp/:/proc/
版权声明 博客名称: 木瓦Blog
本文链接: http://zai.ink/137.html
内容来源: 部分内容可能来源于公共网络,仅供学习交流,如有侵权,请联系博主进行核实删除。
转载说明: 请勿用于商业用途,转载请注明出处!
最后修改:2023 年 11 月 15 日
如果觉得我的文章对你有用,请随意赞赏