What are common pitfalls when using shell_exec in PHP and how can they be avoided?

One common pitfall when using shell_exec in PHP is not properly sanitizing user input, which can lead to command injection vulnerabilities. To avoid this, always validate and sanitize any user input before passing it to shell_exec.

$user_input = $_POST['user_input'];

// Validate and sanitize user input
$clean_input = escapeshellarg($user_input);

// Execute the command safely
$output = shell_exec("ls " . $clean_input);
echo $output;