LoginSignup
2
2

More than 5 years have passed since last update.

phpのcURL(sftp)でファイルをダウンロードする

Last updated at Posted at 2017-12-18

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が指定できない環境もあるようです。

2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2