commit | author | age
|
75471e
|
1 |
<?php |
JK |
2 |
class FtpConnection { |
|
3 |
private static $instances = []; |
|
4 |
private $connection; |
|
5 |
|
|
6 |
static function create(string $host, int $port=21, string $user='anonymous', string $pass='anonymous') : FtpConnection { |
|
7 |
$key = $host."\0".$port."\0".$user."\0".$pass; |
|
8 |
if(!isset(self::$instances[$key])) { |
|
9 |
self::$instances[$key] = new FtpConnection($host, $port, $user, $pass); |
|
10 |
} |
|
11 |
return self::$instances[$key]; |
|
12 |
} |
|
13 |
|
|
14 |
private function __construct(string $host, int $port=21, string $user, string $pass) { |
|
15 |
$this->connection = ftp_connect($host, $port, 10); |
|
16 |
if($this->connection === FALSE) { |
|
17 |
throw new Exception('FTP connection failed'); |
|
18 |
} |
|
19 |
if(!ftp_login($this->connection, $user, $pass)) { |
|
20 |
throw new Exception('FTP login failed'); |
|
21 |
} |
|
22 |
if(!ftp_pasv($this->connection, TRUE)) { |
|
23 |
throw new Exception('Passive FTP request failed'); |
|
24 |
} |
|
25 |
} |
|
26 |
|
|
27 |
public function __destruct() { |
|
28 |
ftp_close($this->connection); |
|
29 |
} |
|
30 |
|
|
31 |
public function size(string $file) : int { |
|
32 |
$remoteSize = ftp_size($this->connection, $file); |
|
33 |
if($remoteSize < 0) { |
|
34 |
throw new Exception('FTP file size fetch failed'); |
|
35 |
} |
|
36 |
return $remoteSize; |
|
37 |
} |
|
38 |
|
|
39 |
|
|
40 |
public function mdtm(string $file) : int { |
|
41 |
$remoteTime = ftp_mdtm($this->connection, $file); |
|
42 |
if($remoteTime < 0) { |
|
43 |
throw new Exception('FTP modification time fetch failed'); |
|
44 |
} |
|
45 |
return $remoteTime; |
|
46 |
} |
|
47 |
|
|
48 |
public function get(string $local_file, string $remote_file, int $mode = FTP_BINARY, int $resumepos = 0) : bool { |
|
49 |
$result = ftp_get($this->connection, $local_file, $remote_file, $mode, $resumepos); |
|
50 |
if($result === FALSE) { |
|
51 |
throw new Exception('FTP file get failed'); |
|
52 |
} |
|
53 |
return $result; |
|
54 |
} |
|
55 |
} |