What potential security risks are involved when using PHP to execute external commands like launching Word for printing?

When using PHP to execute external commands like launching Word for printing, there is a risk of command injection attacks if user input is not properly sanitized. To mitigate this risk, it is important to validate and sanitize any user input before using it in the command execution.

$user_input = $_POST['user_input'];

// Validate and sanitize user input
if (preg_match('/^[a-zA-Z0-9\s]+$/', $user_input)) {
    // Execute command using sanitized user input
    $command = 'start /wait winword.exe /p ' . escapeshellarg($user_input);
    shell_exec($command);
} else {
    echo 'Invalid input';
}