Capture Last Line of exec Output in PHP

When running external terminal commands within a PHP application, you often only need the final result or status message returned by the program. This article explains how to utilize PHP’s native exec() function to execute an external command and directly capture the very last line of its output with minimal code.

Understanding PHP’s exec() Behavior

By design, the exec() function in PHP executes a given command and returns the last line of the output as a string. This makes capturing the final line of an external program’s output extremely straightforward, as you do not need to parse an entire array of output lines.

The basic syntax of the function is:

string exec(string $command, array &$output = null, int &$result_code = null)

Basic Example: Capturing the Last Line

To capture just the last line of the output, assign the return value of exec() directly to a variable.

<?php
// Example command: Listing files
// This will return only the last line of the directory listing
$lastLine = exec('ls -la');

echo "The last line of output is: " . $lastLine;
?>

In this example, even though ls -la produces multiple lines of output, the $lastLine variable will only contain the very last line printed by the command.

Capturing Both the Full Output and Last Line

If you need to inspect the full output but still want easy access to the last line, you can pass a reference variable as the second argument to exec(). PHP will populate this array with every line of the output.

<?php
$outputArray = [];
$resultCode = 0;

// Execute the command
$lastLine = exec('ping -c 3 google.com', $outputArray, $resultCode);

// $lastLine contains the last line
echo "Last Line: " . $lastLine . "\n\n";

// $outputArray contains every line of the output as an array element
echo "Full Output:\n";
print_r($outputArray);
    
// $resultCode contains the return status (0 usually means success)
echo "Status Code: " . $resultCode;
?>

Security Best Practices

When executing external commands, especially when incorporating user input, always sanitize your arguments to prevent command injection vulnerabilities. Use escapeshellarg() or escapeshellcmd() to secure your inputs.

<?php
// Securely passing user input as an argument
$userInput = 'image.png';
$safeArgument = escapeshellarg($userInput);

$lastLine = exec("file " . $safeArgument);
echo $lastLine;
?>