PECL ssh2が使える環境では、
ssh2_connectなどを使って接続するのがいいと思います。
ssh2_系が使えるか確認(使えないパターン)
$ php -r 'ssh2_connect("example.com");'
PHP Fatal error: Call to undefined function ssh2_connect() in Command line code on line 1
ssh2_系が使えなかったので、cURLでやってみる。
$host = 'test.example.com';
$port = 22;
$src = '/home/hoge/remote.txt'; // フルパス
//$src = '/~/remote.txt'; // 相対パス
$dst = './local.txt';
$fh = @fopen($dst, 'w');
if (!$fh){
throw new \Exception("ファイルが保存できません。");
}
$curl = curl_init();
curl_setopt($curl, CURLOPT_FILE, $fh);
// プロトコルの設定
curl_setopt($curl, CURLOPT_PROTOCOLS, CURLPROTO_SFTP);
// 認証は適宜修正(今回は、id:pass)
curl_setopt($curl, CURLOPT_SSH_AUTH_TYPES, CURLSSH_AUTH_PASSWORD);
curl_setopt($curl, CURLOPT_USERPWD,"{$username}:{$password}");
// ポートの設定
curl_setopt($curl, CURLOPT_PORT, $port);
$url = "sftp://{$host}:{$src}";
curl_setopt($curl, CURLOPT_URL, $url);
$ret = curl_exec($curl);
if (!$ret){
// 失敗したときは、ファイル削除した方がいいかも
throw new \Exception("ファイルのダウンロードに失敗しました。");
}
curl_close($curl);
fclose($fh);
注意
CURLPROTO_SFTPが指定できない環境もあるようです。