user364241
user364241

Reputation: 21

How can we execute linux commands from php programs?

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

Upvotes: 0

Views: 260

Answers (3)

BMBM
BMBM

Reputation: 16033

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

Upvotes: 1

Jesse
Jesse

Reputation: 10466

you can use passthru, like so:

$somevar = passthru('echo "Testing1"');
// $somevar now == "Testing1"

or

echo passthru('echo "Testing2"');
// outputs "Testing2"

Upvotes: 3

Digital Human
Digital Human

Reputation: 1637

use exec('command', $output);

print_r($output);

Upvotes: 1

Related Questions