What are best practices for handling user input in PHP to prevent security vulnerabilities when using the exec() function?

When using the exec() function in PHP, it is important to sanitize and validate user input to prevent security vulnerabilities such as command injection attacks. One way to do this is by using escapeshellarg() or escapeshellcmd() functions to escape user input before passing it to the exec() function. Additionally, you can restrict the allowed characters or input format to further enhance security.

$user_input = $_POST['user_input'];

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

// Execute the command safely
$output = exec("some_command $clean_input");

// Output the result
echo $output;