Search code examples
phpraspberry-pireal-time-updates

How To Make a PHP Script Synchronously Update From Terminal Values


Using a Raspberry Pi I created a script which loads the CPU Temperature of the Pi through an Apache Server onto the Browser.

<?php
$temp = exec('vcgencmd measure_temp');

$temp = str_replace('temp=','',$temp);
$temp = str_replace('\'C','',$temp);

echo $temp;

?>

Using the code above I have to manually refresh the page to see the latest value.

It works fine but I'd like to know how I could set this up without having to refresh the browser all the time.

Within the Terminal on the Pi I was able to use the "watch" command which will give me the current value every 0.1 seconds.

But by executing this script, the browser will give me a blank page.

<?php
$temp = exec('watch -n 0.1 vcgencmd measure_temp');

$temp = str_replace('temp=','',$temp);
$temp = str_replace('\'C','',$temp);

echo $temp;

?>

Is there any way to make the script using the "watch" command work with the PHP Script? If not, is there any other way to make it refresh everytime the value changes in the terminal?

Note: I am new to programming and using the Pi.

I would really appreciate any helpful information!

Thank you in advance!


Solution

  • Watch wont work in your case, you can call jquery cdn from official website and then do this function. Do not forget to open console to see what comes back. F12

    Add this into your php file.

    if(isset($_GET)){
    
    $temp = exec('vcgencmd measure_temp');
    
    $temp = str_replace('temp=','',$temp);
    $temp = str_replace('\'C','',$temp);
    
    echo $temp;
    }
    

    Then into your index.html

     $(function() {
        startRefresh();
    });
    
    function startRefresh() {
        setTimeout(startRefresh,1000); // 1000 represents 1 second, free to change
        $.get('index.php', function(data) { // i assume your index.php in same folder with your html file.
            console.log(data);
        });
    }