What are the recommended security measures to implement when executing shell commands from PHP to prevent any vulnerabilities or exploits?

When executing shell commands from PHP, it is crucial to implement security measures to prevent vulnerabilities or exploits, such as command injection attacks. One recommended approach is to use escapeshellarg() or escapeshellcmd() functions to properly escape user input before passing it to the shell.

$user_input = $_POST['user_input'];
$escaped_input = escapeshellarg($user_input);

$output = shell_exec("ls " . $escaped_input);
echo $output;