How can we execute linux commands from php programs? - php

I want to see the output of the following code in the web browser:
code:
<?php
$var = system('fdisk -l');
echo "$var";
?>
When I open this from a web browser there is no output in the web browser. So how can I do this? Please help!
Thanks
Puspa

you can use passthru, like so:
$somevar = passthru('echo "Testing1"');
// $somevar now == "Testing1"
or
echo passthru('echo "Testing2"');
// outputs "Testing2"

use exec('command', $output);
print_r($output);

First of all, be sure that you (=user under which php runs) are allowed to call the external program (OS access rights, safe_mode setting in php.ini). Then you have quite a few options in PHP to call programs via command line. The most common I use are:
system
This function returns false if the command failed or the last line of the returned output.
$lastLine = system('...');
shell_exec or backtick operators
This function/operator return the whole output of the command as a string.
$output = shell_exec('...'); // or:
$output = `...`;
exec
This function returns the last line of the output of the command. But you can give it a second argument that then contains all lines from the command output.
$lastLine = exec('...'); // or capturing all lines from output:
$lastLine = exec('...', $allLines);
Here is the overview of all functions for these usecases: http://de.php.net/manual/en/ref.exec.php

Related

PHP exec() execute last command only?

Here is an example trying to understand exec() function
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
echo exec("id;ls");
?>
When i run this code the result of ls only
Does exec() execute the last command only or it executes both of them and echo the last command ?
You can use shell_exec() instead for this purpose.
On the other hand, exec() returns only last line of the output (by default), but you can provide reference for output array as a second argument.
See the documentation for more info.
exec returns the last line from the result of the command. You have to use output argument. If the output argument is present, then the specified array will be filled with every line of output from the command.
exec("id;ls", $output);
var_dump($output);
you need write a shell script for Linux(excutable with .sh file)

Read output from a Python command in a PHP webapp

I'm trying to read python output from a php webapp.
I'm using $out = shell_exec("./mytest") in the php code to launch the application, and sys.exit("returnvalue") in the python application to return the value.
The problem is that $out doesn't contain my return value.
Instead if I try with $out = shell_exec("ls"), $out variable contain the output of ls command.
If I run ./mytest from terminal it works and I can see the output on my terminal.
sys.exit("returnvalue")
Using a string with sys.exit is used to indicate an error value. So this will show returnvalue in stderr, not stdout. shell_exec() only captures stdout by default.
You probably want to use this in your Python code:
print("returnvalue")
sys.exit(0)
Alternatively, you could also use this in your PHP code to redirect stderr to stdout.
$out = shell_exec("./mytest 2>&1");
(In fact, doing both is probably best, since having stderr disappear can be quite confusing if something unexpected happens).

PHP Put list from Powershell into Array

Code:
$exchangesnapin = "Add-PSSnapin Microsoft.Exchange.Management.PowerShell.E2010";
$output = shell_exec('powershell '.$exchangesnapin.';"get-mailboxdatabase" 2>&1');
echo( '<pre>' );
echo( $output );
echo( '</pre>' );
Result:
Name Server Recovery ReplicationType
---- ------ -------- ---------------
Mailbox Database 0651932265 EGCVMADTEST False None
Mailbox Database 0651932266 EGCVMADTEST False None
I tried with
echo( $output[1] );
The result was only a letter 'N'. I believe its taking the Name column but one character at a time.
$output[1] is 'N', $output[2] is 'a'.
Is there any way I can get the mailbox list into array?
you are trying to execute an external program (powershell) from PHP and have the output as an array.
In order to execute an external program in PHP, you could use:
exec() function
shell_exec() function
system() function
backtick operator
process control extensions
using process control extensions (PCNTL, popen) gives you more control, but takes more code and time. using the execution functions are simpler.
In this situation, using exec() could help you to have the output of powershell in an array whose each index is a line from the powershell output.
<?php
$output = array(); // this would hold the powershell output lines
$return_code = 0; // this would hold the return code from powershell, might be used to detect execution errors
$last_line = exec("powershell {$exchangesnapin} get-mailboxdatabase 2>&1", $output, $return_code);
echo "<pre>";
// print_r($output); view the whole array for debugging
// or iterate over array indexes
foreach($output as $line) {
echo $line . PHP_EOL;
}
echo "</pre>";
?>
Please note that (as the documentation says) if you only want to echo the output of powershell, you could use the passthru() function. using exec() uses memory to store the output of the external program, but using passthru would not use this storage, resulting in less memory usage. But the output could not be used for further processing, and is sent to the PHP standard output right a way.
In the end, please note that external program execution requires careful data validation to reduce the risk of unwanted system effects. Make sure you use escapeshellarg() on the data that constructs the execution command.

how to prevent system() function from printing output in the browser?

I'm using system() PHP function to run some curl commands like this system("curl command here",$output); but it displays results on screen. Any way to avoid this output?
You're using the wrong function for that. According to the docs:
system() is just like the C version of the function in that it executes the given command and outputs the result.
So it always outputs. Use exec­Docs instead which does return (and not output) the programs output:
$last = exec("curl command here", $output, $status);
$output = implode("\n", $output);
Or (just for completeness) use output buffering­Docs:
ob_start();
system("curl command here", $status);
$output = ob_get_clean();
You coud try using output buffering.
ob_start();
system("curl command here",$output);
$result = ob_get_contents();
ob_end_clean();
You could either modify the command string and append " 1>/dev/null 2>&1" or - more elegantly - execute the process with a pipe (see example #2).
For a more refined control over the process' file handles, you can also use proc_open().
The system function displays the output from your command, so you're out of luck there.
What you want is to change system for exec. That function will not display the command's output.
No, you should use PHP curl library

How do I pipe rake output using php?

I'm building a RAKEFILE and I want to display the output on a php generated page as it gets executed.
I tried using system() since the PHP docs mention this:
The system() call also tries to automatically flush the web server's output buffer after each line of output if PHP is running as a server module.
This seems to work with multiple shell comands but when I execute rake I only get the first line:
(in /Users/path/to/proj)
Any ideas?
Cheers!
Try use exec() function
exec($command, $output);
$output is an array
//retrieved data
for($out = '',$x = 0,$len = count($output); $x < $len; $x++) {
$out .= $output[$x] . "\r\n";
}
or simple:
$out = join("\r\n", $output);
The system() call also tries to automatically flush the web server's output buffer after > each line of output if PHP is running as a server module.
This means you would only get the last line of output from the return value. The example in the system() manual page shows that and it suggests to use passthru() to get raw output. I usually use exec() though.
Turs out both functions system() & exec() actually work. The generated rake output when using --verbose isn't taken into consideration though. That's why I was confused. If anyone has more extensive knowledge on the distinction, do share :)

Categories