What are the common pitfalls when using exec() function in PHP to execute external programs?

One common pitfall when using the exec() function in PHP is not properly sanitizing user input, which can lead to security vulnerabilities such as command injection attacks. To solve this issue, always validate and sanitize any user input before passing it to the exec() function. Additionally, it is important to use absolute paths for the command being executed to prevent any potential path traversal attacks.

// Example of properly sanitizing user input before using exec()

$user_input = $_POST['input'];

// Validate and sanitize user input
if (preg_match('/^[a-zA-Z0-9\s]+$/', $user_input)) {
    // Use absolute path for the command being executed
    $command = '/usr/bin/your_command ' . escapeshellarg($user_input);
    
    // Execute the command safely
    exec($command);
} else {
    echo 'Invalid input';
}