How can you ensure that shell_exec() is allowed and safe to use on your web server when executing external commands in PHP?

To ensure that shell_exec() is allowed and safe to use on your web server when executing external commands in PHP, you should carefully sanitize and validate any user input that is passed to the shell_exec() function. Additionally, you should restrict the commands that can be executed to a predefined list of safe commands to prevent any malicious code injection.

$allowed_commands = array("ls", "pwd", "echo"); // Define a list of safe commands
$user_input = $_POST['command']; // Get user input

if (in_array($user_input, $allowed_commands)) {
    $output = shell_exec($user_input); // Execute the command
    echo $output; // Output the result
} else {
    echo "Invalid command"; // Handle invalid commands
}