What are some best practices for handling command execution in PHP to ensure both security and functionality?

When executing shell commands in PHP, it is important to sanitize user input to prevent command injection vulnerabilities. One way to do this is by using escapeshellarg() or escapeshellcmd() functions to escape user input before passing it to the shell. Additionally, it is recommended to use functions like shell_exec() or proc_open() instead of system() or exec() as they provide more control over the command execution.

// Example of executing a command safely using escapeshellarg()
$user_input = $_POST['user_input'];
$escaped_input = escapeshellarg($user_input);
$output = shell_exec("ls " . $escaped_input);
echo $output;