2

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.....

9
  • could you do var_dump(shell_exec("top")); ? That way we'll know more like for example the return type Commented Jun 20, 2017 at 12:19
  • Perhaps top isn't exiting and returning output? If I remember correctly, you might be able to do something like top -n 1 or even top -n 1 -b to just get one page of output and exit. Commented Jun 20, 2017 at 12:21
  • This post should answer your question (: Commented Jun 20, 2017 at 12:22
  • @FMashiro, var_dump(shell_exec("top")); produces same behaviour, i.e. script hangs, no output. Commented Jun 20, 2017 at 12:26
  • Well, script hangs is pretty different from having no output. If the page doesn't load, you may have to check the PHP logs on the server. Commented Jun 20, 2017 at 12:27

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Good god, and I thought being a PHP novice is enough to get the job done ! :) Thanks for your detailed response, I will start looking into Ajax, JScript books.
If you want to display output on the browser by AJAX call, use the command as top -b -n 1

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.