Skip to content

Instantly share code, notes, and snippets.

@naholyr
Created May 23, 2012
Embed
What would you like to do?
SFTP using SSH2 extension
<?php
// Connect to sftp server
function sftp_connect(array $config)
{
if (!function_exists('ssh2_connect')) {
throw new Exception('Extension SSH2 not installed: check server configuration');
}
$options = array_merge(array(
'host' => 'localhost',
'port' => 22,
'methods' => null,
'fingerprint' => null,
'username' => 'user', // SSH username
'auth' => 'none', // 'none', 'key' or 'password'
// if auth == key
'pubkey' => '/path/to/key.pub',
'privkey' => '/path/to/key.rsa',
'passphrase' => null, // may not be supported, randomly, fuck this shit ><
// if auth == password
'password' => null
), $options);
if ($ssh = ssh2_connect($config['host'], $config['port'], $config['methods'])) {
if ($config['fingerprint']) {
$fingerprint = ssh2_fingerprint($ssh, SSH2_FINGERPRINT_MD5 | SSH2_FINGERPRINT_HEX);
if ($fingerprint != $config['fingerprint']) {
throw new Exception(sprintf('Known host fingerprint "%s" does not match %s:%s fingerprint "%s". Possible man-in-the-middle attack ?', $config['fingerprint'], $config['host'], $config['port'], $fingerprint));
}
}
$connected = false;
switch ($config['auth']) {
case 'key':
$connected = ssh2_auth_pubkey_file($ssh, $config['username'], $config['pubkey'], $config['privkey'], $config['passphrase']);
break;
case 'password':
$connected = ssh2_auth_password($ssh, $config['username'], $config['password']);
break;
case 'none':
$connected = ssh2_auth_none($ssh, $config['username']);
break;
default:
throw new Exception(sprintf('Invalid configuration: "%s" is not a valid value for "ssh2_auth". It must be one of "key", "password", or "none".', $config['auth']));
}
if (!$connected) {
throw new Exception(sprintf('Failed authenticating to %s:%s using method %s', $config['host'], $config['port'], $config['auth']));
}
} else {
throw new Exception(sprintf('Failed connecting to %s:%s', $config['host'], $config['port']));
}
return $ssh;
}
// Send file via SSH
function sftp_send_file($source, $dest, $server)
{
if (!is_file($source)) {
throw new Exception(sprintf('Source file "%s" does not exist', $source));
}
// $server = connection options or SSH resource ?
$ssh = is_array($server) ? sftp_connect($server) : $server;
return ssh2_scp_send($ssh, $source, $dest);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment