get system cpu temperature in celsius in php

To get the system CPU temperature in Celsius using PHP, we can make use of the sys_get_temp_dir() function to get the path to the system's thermal zone directory, and then read the contents of the temp file to get the CPU temperature in milli-degrees Celsius. We can then convert the temperature to Celsius by dividing by 1000.

Here is the code:

main.php
<?php
function get_cpu_temperature() {
    $thermal_zone = trim(shell_exec('sys_get_temp_dir'));
    $temp_file = "$thermal_zone/temp";
    $temp = intval(trim(file_get_contents($temp_file))); // in milli-degrees Celsius
    return $temp / 1000; // convert to degrees Celsius
}

$cpu_temp = get_cpu_temperature();
echo "CPU Temperature: $cpu_temp &#8451;"; // display the temperature with Celsius symbol
?>
407 chars
12 lines

Note: This code will only work on systems with thermal zones, such as Linux-based systems.

gistlibby LogSnag