How does escapeshellarg() help prevent injection attacks in PHP?

Injection attacks in PHP can occur when user input is not properly sanitized before being passed to shell commands. The escapeshellarg() function helps prevent injection attacks by escaping special characters in a string, making it safe to use as an argument in shell commands. This function adds backslashes before characters like spaces, quotes, and other special characters, ensuring that the input is treated as a single argument and not as a command or additional options.

$user_input = $_POST['user_input']; // Get user input from a form

$escaped_input = escapeshellarg($user_input); // Escape the user input

// Use the escaped input in a shell command
$output = shell_exec("ls -l " . $escaped_input);

echo $output;