Are there any potential security risks or vulnerabilities when using shell_exec in PHP to retrieve service names?

Using shell_exec in PHP to retrieve service names can pose security risks due to potential command injection vulnerabilities. To mitigate this risk, it is recommended to sanitize user input and validate the input before passing it to shell_exec.

$user_input = $_GET['input']; // Assuming user input is retrieved from a form field

// Sanitize and validate user input
if (preg_match('/^[a-zA-Z0-9_-]+$/', $user_input)) {
    $service_names = shell_exec('systemctl list-units --type=service | grep ' . escapeshellarg($user_input));
    echo $service_names;
} else {
    echo "Invalid input";
}