What best practices should be followed when using shell_exec in PHP to avoid security vulnerabilities?

When using shell_exec in PHP, it is important to sanitize user input to prevent command injection attacks. One way to do this is by using escapeshellarg() or escapeshellcmd() functions to escape any user input before passing it to shell_exec. Additionally, it is recommended to validate and restrict the input to only allow expected values to further reduce the risk of vulnerabilities.

$user_input = $_POST['input']; // Assuming user input is coming from a form

// Sanitize user input using escapeshellarg()
$command = 'ls ' . escapeshellarg($user_input);

// Execute the sanitized command using shell_exec
$output = shell_exec($command);

// Output the result
echo $output;