What are some best practices for securely using exec()/shell_exec() in PHP?

When using exec() or shell_exec() in PHP, it is important to sanitize user input to prevent command injection attacks. One way to do this is by using escapeshellarg() to escape any user input that is passed to the command. Additionally, it is recommended to validate and restrict the input to only allow certain characters or values.

$user_input = $_POST['user_input']; // Assuming user input is coming from a form

// Sanitize user input using escapeshellarg()
$escaped_input = escapeshellarg($user_input);

// Execute the command with the sanitized input
$output = shell_exec("command " . $escaped_input);

// Use the output as needed
echo $output;