Search code examples
phpshell-exec

How to display output of 'top' command on web browser using Php


I have a simple php script 'top.php' with shell_exec function.

Code:

<?php
echo shell_exec("top");
?>

What I am looking for is to view results of 'top' command on a web browser. So, if I access http://192.168.1.1/top.php I want to see results of top command. It is essential to view results of top command periodically as you would see in a command line terminal.

However, when I access 'http://192.168.1.1/top.php' on web browser, it does not display anything. Same behaviour when I execute top.php on command line (as 'php top.php').

I am not sure what or where it is going wrong.....


Solution

  • top on the command line by default just keeps running, so I suspect what's happening here is that it's not exiting and returning output to PHP. The -n 1 flag should address that:

    <?php
    echo shell_exec("top -n 1");
    ?>
    

    This would give you one "page" of output from top to display on your webpage. In order to refresh it, you would of course just refresh the webpage.

    To make something a little smoother (where you don't have to refresh the page), you could have a page which makes an AJAX request to this PHP script and then displays the output on the page. That AJAX request could then be scheduled with setInterval() in JavaScript to occur ever X seconds as you see fit.