What are the best practices for handling output from shell commands executed by PHP scripts?

When executing shell commands in PHP scripts, it is important to properly handle the output to avoid security vulnerabilities such as command injection. The best practice is to use functions like `shell_exec()` or `exec()` to capture the output securely and then sanitize or validate it before displaying or using it in your application.

// Example of executing a shell command and capturing the output securely
$command = 'ls -l';
$output = shell_exec($command);

// Sanitize or validate the output before using it
if ($output !== null) {
    echo "Output: " . htmlspecialchars($output);
} else {
    echo "Error executing command.";
}