What are the potential security risks of using shell_exec in PHP, and how can they be mitigated?

Using shell_exec in PHP can pose security risks, such as allowing for command injection attacks if user input is not properly sanitized. To mitigate these risks, it is important to validate and sanitize any user input before passing it to shell_exec. Additionally, limiting the commands that can be executed and using escapeshellarg() or escapeshellcmd() to escape any arguments can help prevent potential vulnerabilities.

$user_input = $_POST['user_input'];

// Validate and sanitize user input
$validated_input = filter_var($user_input, FILTER_SANITIZE_STRING);

// Limit the commands that can be executed
$allowed_commands = array('ls', 'echo', 'cat');
if (in_array($validated_input, $allowed_commands)) {
    $output = shell_exec($validated_input);
    echo $output;
} else {
    echo "Invalid command";
}