|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace SF2Helpers\SFTPBundle\SFTP; |
|
4
|
|
|
|
|
5
|
|
|
class SFTP implements ConnectionInterface, ResourceTransferInterface |
|
6
|
|
|
{ |
|
7
|
|
|
private $connection; // connection instance |
|
8
|
|
|
|
|
9
|
|
|
private $sftp; // established sftp |
|
10
|
|
|
|
|
11
|
|
|
|
|
12
|
|
|
public function __construct() |
|
13
|
|
|
{ |
|
14
|
|
|
} |
|
15
|
|
|
|
|
16
|
|
|
public function connect($host, $username, $password=NULL, string $pubkeyfile=NULL, string $privkeyfile=NULL) |
|
17
|
|
|
{ |
|
18
|
|
|
$connection = ssh2_connect($host); |
|
19
|
|
|
|
|
20
|
|
|
if ($password.is_null()) { |
|
21
|
|
|
ssh2_auth_agent($connection, $username); |
|
22
|
|
|
} else { |
|
23
|
|
|
ssh2_auth_password($connection, $username, $password); |
|
24
|
|
|
} |
|
25
|
|
|
|
|
26
|
|
|
$sftp = ssh2_sftp($connection); |
|
27
|
|
|
$this->connection = $connection; |
|
28
|
|
|
$this->sftp = $sftp; |
|
29
|
|
|
} |
|
30
|
|
|
|
|
31
|
|
|
public function connectWithKey($host, $username, string $pubkeyfile, string $privkeyfile, string $passphrase=NULL) |
|
|
|
|
|
|
32
|
|
|
{ |
|
33
|
|
|
$connection = ssh2_connect($host); |
|
34
|
|
|
|
|
35
|
|
|
ssh2_auth_pubkey_file($connection, $username, $pubkeyfile, $privkeyfile, $password); |
|
|
|
|
|
|
36
|
|
|
|
|
37
|
|
|
$sftp = ssh2_sftp($connection); |
|
38
|
|
|
$this->connection = $connection; |
|
39
|
|
|
$this->sftp = $sftp; |
|
40
|
|
|
} |
|
41
|
|
|
|
|
42
|
|
View Code Duplication |
public function copy($remoteFile, $localFile) |
|
|
|
|
|
|
43
|
|
|
{ |
|
44
|
|
|
$sftp = "ssh2.sftp://$this->sftp"; |
|
45
|
|
|
$data = file_get_contents($sftp . $remoteFile); |
|
46
|
|
|
if (!$data) { |
|
47
|
|
|
throw new \Exception('File can`t be loaded from server'); |
|
48
|
|
|
} |
|
49
|
|
|
file_put_contents($localFile, $data); |
|
50
|
|
|
} |
|
51
|
|
|
|
|
52
|
|
View Code Duplication |
public function send($localFile, $remoteFile) |
|
|
|
|
|
|
53
|
|
|
{ |
|
54
|
|
|
$sftp = "ssh2.sftp://$this->sftp"; |
|
55
|
|
|
$data = file_get_contents($localFile); |
|
56
|
|
|
if (!file_put_contents($sftp . $remoteFile, $data)) { |
|
57
|
|
|
throw new \Exception('File could not be uploaded to server'); |
|
58
|
|
|
} |
|
59
|
|
|
} |
|
60
|
|
|
|
|
61
|
|
|
public function getFilesList($dir) { |
|
62
|
|
|
$handle = opendir("ssh2.sftp://$this->sftp" . $dir); |
|
63
|
|
|
$files = array(); |
|
64
|
|
|
|
|
65
|
|
|
while (false != ($entry = readdir($handle))){ |
|
|
|
|
|
|
66
|
|
|
$files[] = $entry; |
|
67
|
|
|
} |
|
68
|
|
|
|
|
69
|
|
|
return $files; |
|
70
|
|
|
} |
|
71
|
|
|
|
|
72
|
|
|
public function disconnect() |
|
73
|
|
|
{ |
|
74
|
|
|
ssh2_exec($this->connection, 'exit'); |
|
75
|
|
|
unset($this->connection); |
|
76
|
|
|
} |
|
77
|
|
|
} |
|
78
|
|
|
|
This check looks from parameters that have been defined for a function or method, but which are not used in the method body.