get server ram with php

后端 未结 9 1654
抹茶落季
抹茶落季 2020-12-05 00:19

Is there a way to know the avaliable ram in a server (linux distro) with php (widthout using linux commands)?

edit: sorry, the objective is to be aware of the ram av

9条回答
  •  北荒
    北荒 (楼主)
    2020-12-05 00:56

    // helpers

    /**
     * @return array|null
     */
    protected function getSystemMemInfo()
    {
        $meminfo = @file_get_contents("/proc/meminfo");
        if ($meminfo) {
            $data = explode("\n", $meminfo);
            $meminfo = [];
            foreach ($data as $line) {
                if( strpos( $line, ':' ) !== false ) {
                    list($key, $val) = explode(":", $line);
                    $val = trim($val);
                    $val = preg_replace('/ kB$/', '', $val);
                    if (is_numeric($val)) {
                        $val = intval($val);
                    }
                    $meminfo[$key] = $val;
                }
            }
            return $meminfo;
        }
        return  null;
    }
    
    // example call to check health
    public function check() {
        $memInfo = $this->getSystemMemInfo();
        if ($memInfo) {
            $totalMemory = $memInfo['MemTotal'];
            $freeMemory = $memInfo['MemFree'];
            $swapTotalMemory = $memInfo['SwapTotal'];
            $swapFreeMemory = $memInfo['SwapFree'];
            if (($totalMemory / 100.0) * 30.0 > $freeMemory) {
                if (($swapTotalMemory / 100.0) * 50.0 > $swapFreeMemory) {
                    return new Failure('Less than 30% free memory and less than 50% free swap space');
                }
                return new Warning('Less than 30% free memory');
            }
        }
        return new Success('ok');
    }
    

提交回复
热议问题