2

Executing unix shell commands using PHP Running shell commands using PHP script Execute a shell command through php and display it in browser? I have already referred to the above links. But, I'm experiencing an issue in displaying the linux shell command process in the browser. My linux command: top -n 1 and wanted to display them using php in the browser..

myscript.php
<?php
$var = shell_exec('top -n 1');
echo "<pre>$var</pre>";
?>

Now, when I refresh my browser, I'm unable to see the output in the browser.

Community
  • 1
  • 1
KumarRana
  • 103
  • 1
  • 7

3 Answers3

1

Ok, I see your problem Rana. There some shell commands in linux needed to be set along with the TERM enviroment variable. top is one of them. In addition -b flag must be used in order to get the result from the output buffer, that in this case is the terminal... Try this code:

<?php
$var = shell_exec('TERM=xterm /usr/bin/top -n1 -b');
echo "<pre>$var</pre>";
?>
Andreas Venieris
  • 452
  • 3
  • 15
  • Hey Andreas, thats worked!!. I appreciate your efforts. Thanks alot. Now I can execute the shell command with the php script and display it in the browser. – KumarRana May 03 '15 at 20:14
0

Since the user browser is not an interactive terminal then we have to execute your last command in every postback, in order to simlate the linux top command.

Andreas Venieris
  • 452
  • 3
  • 15
  • Hi Andreas, so what can we perform at this point to execute the top command using my php script. I wanted to display the info on browser once the php script shell_exec command is requested. – KumarRana May 03 '15 at 09:23
0

Your script looks OK, let's make sure that your environment is correctly set up by changing the script to do something very simple. Try replacing all code with something like

<?php
echo "Hello World";

If that works, then some further debugging: Are you on a shared webhost where PHP is possibly configured to disable execution of scripts? See if shell_exec is disabled as detailed here (replace the string exec with shell_exec).

Community
  • 1
  • 1
Martin Konecny
  • 57,827
  • 19
  • 139
  • 159
  • Hi Martin, my script is working well with ls -l and other linux commands. But only the top command is not working. – KumarRana May 03 '15 at 09:21