How can the use of shell_exec() in PHP pose security risks and what are the best practices to avoid them?

Using shell_exec() in PHP can pose security risks because it allows the execution of shell commands on the server, which can lead to command injection vulnerabilities. To mitigate this risk, it is recommended to sanitize and validate any user input before passing it to shell_exec(), and to avoid using user input directly in the command string.

$user_input = $_POST['input'];

// Sanitize and validate user input
$clean_input = escapeshellarg($user_input);

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