search
HomeBackend DevelopmentPHP TutorialPHP implementation code to obtain Linux server CPU, memory, and hard disk usage

  1. define("MONITORED_IP", "172.16.0.191"); //The monitored server IP address is also the local address
  2. define("DB_SERVER", "172.16.7.2"); //The IP address of the server where the data is stored
  3. define("DB_USER", "root");
  4. define("DB_PWD","111111");
  5. define("DB_NMAE","performance");
  6. class MyConnect{
  7. public function connect($db_server,$db_user,$db_pwd,$db_name){
  8. $conn = mysql_connect($db_server,$db_user,$db_pwd);
  9. if (!$conn){
  10. die('Failed to connect to database: ' . mysql_error());
  11. }
  12. $flag = mysql_select_db($db_name,$conn);
  13. if(!$flag){
  14. echo "

    Database connection error! p>";exit();

  15. }else{
  16. mysql_query("SET NAMES UTF8");
  17. }
  18. }
  19. }
  20. ?>
Copy code

2. Get the file get_used_status for server performance data. php

  1. /**

  2. * Get server performance CPU, memory, hard disk and other usage rates
  3. * Edit bbs.it-home.org
  4. */
  5. /*Connection data begin*/
  6. include("conn.php");
  7. $obj_MyConnect = new MyConnect() ;
  8. $obj_MyConnect -> connect(DB_SERVER,DB_USER,DB_PWD,DB_NMAE);
  9. /*Connect data end*/
  10. function get_used_status(){
  11. $fp = popen('top -b -n 2 | grep -E "^(Cpu|Mem|Tasks)"',"r");//Get the system cpu and memory usage at a certain moment
  12. $rs = "";
  13. while(!feof($fp)){
  14. $rs .= fread($fp,1024);
  15. }
  16. pclose($fp);
  17. $sys_info = explode("n",$rs);
  18. $tast_info = explode(", ",$sys_info[3]);//Process array

  19. $cpu_info = explode(",",$sys_info[4]); //CPU occupancy array
  20. $mem_info = explode(",",$sys_info[5 ]); //Memory occupancy array
  21. //Number of running processes

  22. $tast_running = trim(trim($tast_info[1],'running'));
  23. / /CPU usage
  24. $cpu_usage = trim(trim($cpu_info[0],'Cpu(s): '),'%us'); //Percentage
  25. //Memory usage
  26. $mem_total = trim(trim ($mem_info[0],'Mem: '),'k total');
  27. $mem_used = trim($mem_info[1],'k used');
  28. $mem_usage = round(100*intval($mem_used) /intval($mem_total),2); //Percent
  29. /*Hard disk usage begin*/

  30. $fp = popen('df -lh | grep -E "^(/ )"',"r");
  31. $rs = fread($fp,1024);
  32. pclose($fp);
  33. $rs = preg_replace("/s{2,}/",' ',$rs) ; //Replace multiple spaces with "_"
  34. $hd = explode(" ",$rs);
  35. $hd_avail = trim($hd[3],'G'); //Disk available space size unit G
  36. $hd_usage = trim($hd[4],'%'); //Mount point percentage
  37. //print_r($hd);
  38. /*Hard disk usage end*/
  39. //Detection time
  40. $fp = popen("date +"%Y-%m-%d %H:%M"","r");
  41. $rs = fread($fp,1024);
  42. pclose($fp);
  43. $detection_time = trim($rs);
  44. /*Get IP address begin*/
  45. /*
  46. $fp = popen('ifconfig eth0 | grep -E "(inet addr)"','r');
  47. $rs = fread($fp,1024);
  48. pclose($fp);
  49. $rs = preg_replace("/s{2,}/",' ',trim($rs)); //Replace multiple spaces with " _”
  50. $rs = explode(" ",$rs);
  51. $ip = trim($rs[1],'addr:');
  52. */
  53. /*Get IP addressend*/
  54. /*
  55. $ file_name = "/tmp/data.txt"; // Absolute path: homedata.dat
  56. $file_pointer = fopen($file_name, "a+"); // "w" is a mode, see below for details
  57. fwrite($ file_pointer,$ip); // First cut the file to 0 bytes, then write
  58. fclose($file_pointer); // End
  59. */
  60. return array('cpu_usage'=>$cpu_usage,' mem_usage'=> /echo date("Y-m-d H:i:s",time())."
    ";
  61. $status=get_used_status();
  62. $sql = "insert into performance(ip,cpu_usage,mem_usage, hd_avail,hd_usage,tast_running,detection_time) ";
  63. $sql .= " value('".MONITORED_IP."','".$status['cpu_usage']."','".$status['mem_usage'] ."','".$status['hd_avail']."','".$status['hd_usage']."','".$status['tast_running']."','".$ status['detection_time']."')";
  64. $query = mysql_query($sql) or die("SQL statement execution failed!");
  65. unset($status);
  66. //echo date("Y-m-d H :i:s",time())."
    ";
  67. ?>
  68. Copy code


Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
What is the best way to send an email using PHP?What is the best way to send an email using PHP?May 08, 2025 am 12:21 AM

ThebestapproachforsendingemailsinPHPisusingthePHPMailerlibraryduetoitsreliability,featurerichness,andeaseofuse.PHPMailersupportsSMTP,providesdetailederrorhandling,allowssendingHTMLandplaintextemails,supportsattachments,andenhancessecurity.Foroptimalu

Best Practices for Dependency Injection in PHPBest Practices for Dependency Injection in PHPMay 08, 2025 am 12:21 AM

The reason for using Dependency Injection (DI) is that it promotes loose coupling, testability, and maintainability of the code. 1) Use constructor to inject dependencies, 2) Avoid using service locators, 3) Use dependency injection containers to manage dependencies, 4) Improve testability through injecting dependencies, 5) Avoid over-injection dependencies, 6) Consider the impact of DI on performance.

PHP performance tuning tips and tricksPHP performance tuning tips and tricksMay 08, 2025 am 12:20 AM

PHPperformancetuningiscrucialbecauseitenhancesspeedandefficiency,whicharevitalforwebapplications.1)CachingwithAPCureducesdatabaseloadandimprovesresponsetimes.2)Optimizingdatabasequeriesbyselectingnecessarycolumnsandusingindexingspeedsupdataretrieval.

PHP Email Security: Best Practices for Sending EmailsPHP Email Security: Best Practices for Sending EmailsMay 08, 2025 am 12:16 AM

ThebestpracticesforsendingemailssecurelyinPHPinclude:1)UsingsecureconfigurationswithSMTPandSTARTTLSencryption,2)Validatingandsanitizinginputstopreventinjectionattacks,3)EncryptingsensitivedatawithinemailsusingOpenSSL,4)Properlyhandlingemailheaderstoa

How do you optimize PHP applications for performance?How do you optimize PHP applications for performance?May 08, 2025 am 12:08 AM

TooptimizePHPapplicationsforperformance,usecaching,databaseoptimization,opcodecaching,andserverconfiguration.1)ImplementcachingwithAPCutoreducedatafetchtimes.2)Optimizedatabasesbyindexing,balancingreadandwriteoperations.3)EnableOPcachetoavoidrecompil

What is dependency injection in PHP?What is dependency injection in PHP?May 07, 2025 pm 03:09 PM

DependencyinjectioninPHPisadesignpatternthatenhancesflexibility,testability,andmaintainabilitybyprovidingexternaldependenciestoclasses.Itallowsforloosecoupling,easiertestingthroughmocking,andmodulardesign,butrequirescarefulstructuringtoavoidover-inje

Best PHP Performance Optimization TechniquesBest PHP Performance Optimization TechniquesMay 07, 2025 pm 03:05 PM

PHP performance optimization can be achieved through the following steps: 1) use require_once or include_once on the top of the script to reduce the number of file loads; 2) use preprocessing statements and batch processing to reduce the number of database queries; 3) configure OPcache for opcode cache; 4) enable and configure PHP-FPM optimization process management; 5) use CDN to distribute static resources; 6) use Xdebug or Blackfire for code performance analysis; 7) select efficient data structures such as arrays; 8) write modular code for optimization execution.

PHP Performance Optimization: Using Opcode CachingPHP Performance Optimization: Using Opcode CachingMay 07, 2025 pm 02:49 PM

OpcodecachingsignificantlyimprovesPHPperformancebycachingcompiledcode,reducingserverloadandresponsetimes.1)ItstorescompiledPHPcodeinmemory,bypassingparsingandcompiling.2)UseOPcachebysettingparametersinphp.ini,likememoryconsumptionandscriptlimits.3)Ad

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.