-3

Is it possible to display the commands like 'top' on webpage using php?

   <?php
      echo shell_exec('top');
   ?>
Phil
  • 157,677
  • 23
  • 242
  • 245
Elated
  • 29
  • 6
  • i mean is it possible to display the interactive shell command's output in browser? – Elated Oct 24 '13 at 03:59
  • Phil for 'top' command we have the 'ps' but is it impossible to display the output of other interactive shell to browser? – Elated Oct 24 '13 at 04:01
  • Use this: `$str = exec("top -bn1");` – mvp Oct 24 '13 at 04:04
  • top is OK and for commands like tcptrack -i [interface] – Elated Oct 24 '13 at 04:09
  • In addition being interactive only, `tcptrack` requires `sudo`, which php typically cannot execute (unless you are willing to give sudo access to apache user `www-data`) – mvp Oct 24 '13 at 04:12
  • let's say www-data has the root access ....then – Elated Oct 24 '13 at 04:17
  • you cannot do this for *any* interactive command, but only for those which have an option to dump data once (like `top` has `top -bn1` for that) – mvp Oct 24 '13 at 04:39

2 Answers2

2

maybe this:

<?php
$output = null;
exec('top -n 1', $output);
var_dump($output);
?>
Teddybugs
  • 1,232
  • 1
  • 12
  • 37
2

If I understand your question correctly, you're trying to get an interactive program showing on the client with live updates. This is not possible as you've demonstrated.

It seems you may not understand what's going on with PHP. PHP runs on the server before the page is downloaded by the client. The client then gets a 'snapshot' of the page as the server rendered it. Once the page is loaded on the user's machine, the server cannot touch the page.

To get interactive content, you have a few options (from least desirable and easiest to most desirable and most involved):

  • refresh the page
  • make periodic requests for updates (AJAX)
  • have the server push down changes (COMET, WebSockets)

Another problem is that interactive commands like top use a bunch of terminal-specific (refresh the terminal, rewrite bits of text, etc.) that will mess up the output in the browser. You'll need to do something like @David said and get a snapshot of the output and get that to the user periodically (choose one from above).

There are lots of libraries and tutorials for PHP available for whichever route you choose.

beatgammit
  • 19,817
  • 19
  • 86
  • 129
  • Sorry but I didn't get my answer. I just want the snapshot of any interactive command. – Elated Oct 24 '13 at 04:24
  • I'm afraid the answer will be command specific then. Interactive commands are visual and aren't designed to be processed by a computer. Some commands, like `top`, will provide a non-interactive switch. For that, use @David's answer. – beatgammit Oct 24 '13 at 04:31