LoginSignup
31
29

More than 5 years have passed since last update.

PHP で SFTP

Last updated at Posted at 2015-08-05

phpseclib

phpseclib なら簡単です。

$ composer require phpseclib/phpseclib:\*
<?php
require __DIR__ . '/vendor/autoload.php';

$sftp = new Net_SFTP('ore-no-server.example.com');

$keyfile = '/path/to/ore-no-key';

$key = new Crypt_RSA();
$key->loadKey(file_get_contents($keyfile));

if (!$sftp->login('ore', $key)) {
    exit('Login Failed');
}

echo $sftp->pwd() . "\r\n";
$sftp->put('filename.ext', 'hello, world!');
print_r($sftp->nlist());

↑の例は公開鍵認証ですが、次のようにすればパスワード認証もできます。

<?php
require __DIR__ . '/vendor/autoload.php';

$sftp = new Net_SFTP('ore-no-server.example.com');

if (!$sftp->login('ore', 'ore-no-password')) {
    exit('Login Failed');
}

echo $sftp->pwd() . "\r\n";
$sftp->put('filename.ext', 'hello, world!');
print_r($sftp->nlist());

phpseclib 2.0.0

コメントでの @kuwa72 さんからの指摘の通り、最新の 2.0.0 だと名前空間が使われているため、次のように変更する必要があります。

<?php
require __DIR__ . '/vendor/autoload.php';

use phpseclib\Net\SFTP;
use phpseclib\Crypt\RSA;

$sftp = new SFTP('ore-no-server.example.com');

$keyfile = '/path/to/ore-no-key';

$key = new RSA();
$key->loadKey(file_get_contents($keyfile));

if (!$sftp->login('ore', $key)) {
    exit('Login Failed');
}

echo $sftp->pwd() . "\r\n";
$sftp->put('filename.ext', 'hello, world!');
print_r($sftp->nlist());

pecl ssh2

拡張にもあるけどあんまりメンテナンスされている感じがしないので使うのはやめておきます。

31
29
3

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
31
29