What are the differences between using exec and passthru to run external commands in PHP?
When running external commands in PHP, it's important to choose the right function based on the desired behavior. The main differences between exec and passthru are how they handle the output of the command. - exec(): Returns the last line of the command output, discarding the rest. - passthru(): Outputs the command output directly to the browser or console without any processing. To choose between exec and passthru, consider whether you need to capture the output for further processing or simply display it as is.
// Using exec to capture output
$output = [];
exec('ls -l', $output);
foreach ($output as $line) {
echo $line . "\n";
}
// Using passthru to directly output command result
passthru('ls -l');