What are some best practices for securely executing sudo commands in PHP scripts?

When executing sudo commands in PHP scripts, it is important to follow best practices to ensure security. One common approach is to use the `sudo` command with a specific command that needs elevated privileges, rather than running the entire PHP script with sudo. This limits the potential impact of security vulnerabilities in the script. Additionally, it is recommended to validate user input and sanitize any command parameters to prevent injection attacks.

<?php

// Validate and sanitize user input
$command = escapeshellcmd('sudo ls -l');

// Execute the sudo command
$output = shell_exec($command);

// Output the result
echo $output;

?>