As you've already seen, when using shell_exec you have to chain your "real" command with echo $? to get the exit status:

 $output_including_status = shell_exec("command 2>&1; echo $?");

but if you want the clean way, then you want to use the exec function, which allows a 3rd agument explicitly for this purpose.

Answer from Tony Miller on Stack Overflow
🌐
PHP
php.net › manual › en › function.shell-exec.php
PHP: shell_exec - Manual
This function can return null both when an error occurs or the program produces no output. It is not possible to detect execution failures using this function. exec() should be used when access to the program exit code is required. An E_WARNING level error is generated when the pipe cannot be established. ... If you're trying to run a command such as "gunzip -t" in shell_exec and getting an empty result, you might need to add 2>&1 to the end of the command, eg: Won't always work: echo shell_exec("gunzip -c -t $path_to_backup_file"); Should work: echo shell_exec("gunzip -c -t $path_to_backup_file 2>&1"); In the above example, a line break at the beginning of the gunzip output seemed to prevent shell_exec printing anything else.
🌐
BCCNsoft
doc.bccnsoft.com › docs › php-docs-7-en › function.shell-exec.html
Execute command via shell and return the complete output as a string
This function can return NULL both when an error occurs or the program produces no output. It is not possible to detect execution failures using this function. exec() should be used when access to the program exit code is required. ... This function is disabled when PHP is running in safe mode.
🌐
Linux Tip
linuxscrew.com › home › programming › php › php shell_exec function: how to use it [with examples]
PHP shell_exec Function: How to Use It [With Examples]
February 23, 2021 - $fileList = shell_exec('ls -la'); echo "<pre>$fileList</pre>"; The output is then returned as a string and assigned to the variable $fileList, ready for output. In the above example, $fileList is wrapped in <pre> HTML tags so that the output ...
🌐
GeeksforGeeks
geeksforgeeks.org › php › php-shell_exec-vs-exec-function
PHP shell_exec() vs exec() Function - GeeksforGeeks
July 11, 2025 - The shell_exec() function in PHP executes a command via the shell and returns the complete output as a string.
Top answer
1 of 4
122

To read the output of a process, popen() is the way to go. Your script will run in parallel with the program and you can interact with it by reading and writing it's output/input as if it was a file.

But if you just want to dump it's result straight to the user you can cut to the chase and use passthru():

echo '<pre>';
passthru($cmd);
echo '</pre>';

If you want to display the output at run time as the program goes, you can do this:

while (@ ob_end_flush()); // end all output buffers if any

$proc = popen($cmd, 'r');
echo '<pre>';
while (!feof($proc))
{
    echo fread($proc, 4096);
    @ flush();
}
echo '</pre>';

This code should run the command and push the output straight to the end user at run time.

More useful information

Note that if you are using sessions then having one of those running will prevent the user from loading other pages, as sessions enforce that concurrent requests cannot happen. To prevent this from being a problem, call session_write_close() before the loop.

If your server is behind a nginx gateway, then the nginx buffering may be disruptive to the desired behavior. Set the header header('X-Accel-Buffering: no'); to hint nginx that it shouldn't do that. As headers are sent first, this has to be called in the beginning of the script, before any data is sent.

2 of 4
26

First of all, thanks Havenard for your snippet - it helped a lot!

A slightly modified version of Havenard's code which i found useful.

<?php
/**
 * Execute the given command by displaying console output live to the user.
 *  @param  string  cmd          :  command to be executed
 *  @return array   exit_status  :  exit status of the executed command
 *                  output       :  console output of the executed command
 */
function liveExecuteCommand($cmd)
{

    while (@ ob_end_flush()); // end all output buffers if any

    $proc = popen("$cmd 2>&1 ; echo Exit status : live_output     = "";
    $complete_output = "";

    while (!feof($proc))
    {
        $live_output     = fread($proc, 4096);
        $complete_output = $complete_output . $live_output;
        echo "$live_output";
        @ flush();
    }

    pclose($proc);

    // get exit status
    preg_match('/[0-9]+complete_output, $matches);

    // return exit status and intended output
    return array (
                    'exit_status'  => intval($matches[0]),
                    'output'       => str_replace("Exit status : " . $matches[0], '', $complete_output)
                 );
}
?>

Sample Usage :

$result = liveExecuteCommand('ls -la');

if($result['exit_status'] === 0){
   // do something if command execution succeeds
} else {
    // do something on failure
}
🌐
GitHub
github.com › scipag › PHPUtilities › blob › master › shell.php
PHPUtilities/shell.php at master · scipag/PHPUtilities
$methodArray[] = "shell_exec"; } · // Testing backticks · $return = ""; $output = ""; $output = `$cmd`; · if (strlen($output) > 0) { · $methodArray[] = "backticks"; } · // Testing passthru() · $return = ""; $output = ""; ob_start(); passthru($cmd, $return); $output = ob_get_contents(); ob_end_clean(); if (strlen($output[0]) > 0 && $return == 0) { $methodArray[] = "passthru"; } ·
Author   scipag
🌐
Digital Point
forums.digitalpoint.com › threads › capture-shell_exec-output.1479445
Capture shell_exec output
August 31, 2009 - Hey guys, I need to capture the shell_exec output even if it fails. I'm trying to convert a video using ffmpeg and when I run shell_exec it returns...
Find elsewhere
🌐
LinuxQuestions.org
linuxquestions.org › questions › programming-9 › php-output-the-result-of-exec-$command-210217
php: output the result of exec( $command )
July 27, 2004 - I want to develop a console for php and I wanted to know how to retreive and output the result of a unix command. At first I outputed the command to a
🌐
Scaler
scaler.com › home › topics › php exec() function
PHP exec() Function - Scaler Topics
March 18, 2024 - It does not return the output directly to the browser or calling script. shell_exec(): The shell_exec() function executes the command and returns the output directly to the browser or calling script, allowing you to display or manipulate the ...
🌐
OnlinePHP
onlinephp.io › shell-exec › manual
shell_exec - OnlinePHP.io Example
Donate/Get Premium · Login / Register ... · shell_exec · PHP 4, PHP 5, PHP 7, PHP 8 · shell_exec - Execute command via shell and return the complete output as a string ·...
🌐
Linux Hint
linuxhint.com › execute_shell_command_php
Execute Shell Command in PHP using exec() – Linux Hint
PHP has some built-in functions to execute system-related commands. exec() is one of them. It is used to execute shell commands or any program from the PHP script. How this function can be used in PHP are shown in this tutorial. string exec ( string $command [, array &$output [, int &$return_var ]] )
🌐
Delft Stack
delftstack.com › home › howto › php › php shell_exec
The PHP shell_exec() and exec() Functions | Delft Stack
February 26, 2025 - This function is particularly useful when you want to capture the output of a command for further processing or display. Here’s a simple example of how to use shell_exec(): <?php $output = shell_exec('ls -l'); echo $output; ?>