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.

3 Answers 3

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>";
?>
Sign up to request clarification or add additional context in comments.

1 Comment

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

1 Comment

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

1 Comment

Hi Martin, my script is working well with ls -l and other linux commands. But only the top command is not working.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.