How can PHP developers securely handle passwords when using shell_exec for SSH or SCP commands?

When using shell_exec for SSH or SCP commands in PHP, developers should avoid passing passwords directly in the command string to prevent exposing them in the process list. Instead, they can use SSH keys for authentication or utilize tools like expect to securely handle passwords.

<?php
// Using SSH keys for authentication
$command = 'ssh -i /path/to/private_key user@hostname ls';
$output = shell_exec($command);

// Using expect to securely handle passwords
$command = 'expect -c "spawn scp file.txt user@hostname:/path/to/destination; expect password; send password_here\n; interact"';
$output = shell_exec($command);
?>