Files
pgserver3.0/pgserver/application/lib/SFTPConnection.php
annnj-company 130c1026c4 first commit
2026-04-17 18:29:53 +08:00

86 lines
2.5 KiB
PHP

<?php
namespace app\lib;
use think\Exception;
use think\facade\Log;
class SFTPConnection
{
private $connection;
private $sftp;
public function __construct($host, $port=22)
{
$this->connection = @ssh2_connect($host, $port);
if (! $this->connection)
throw new Exception("Could not connect to $host on port $port.");
}
public function login($user_name, $password)
{
if (! @ssh2_auth_password($this->connection, $user_name, $password))
throw new Exception("Could not authenticate with user_name $user_name " .
"and password $password.");
$this->sftp = @ssh2_sftp($this->connection);
if (! $this->sftp)
throw new Exception("Could not initialize SFTP subsystem.");
}
public function fileIsExists($remote_file)
{
$sftp = $this->sftp;
$resource = "ssh2.sftp://{$sftp}" . $remote_file;
return file_exists($resource);
}
public function getFile( $remote_file){
$sftp = $this->sftp;
$resource = "ssh2.sftp://{$sftp}" . $remote_file;
return file_get_contents($resource);
}
public function uploadFile($local_file, $path, $remote_file)
{
$sftp = $this->sftp;
// $findChar = '/';
//
// $pos1 = strripos($remote_file, $findChar);
// $path =substr($remote_file, 0, $pos1);
//$is_exist = $sftp->dir_exits($path);//判断文件夹是否存在
//$path = '/cebbank/llz/send/20230326';
//if ($is_exist === false) {
//ssh2_sftp_mkdir($sftp, '/home/user_name/newdir');
/* Or: mkdir("ssh2.sftp://$sftp/home/user_name/newdir"); */
if (!is_dir("ssh2.sftp://".intval($sftp) . $path)) {
ssh2_sftp_mkdir($sftp, $path,0777,true);
}//不存在则创建
$stream = @fopen("ssh2.sftp://".intval($sftp) . $remote_file, 'wr');
if (! $stream)
throw new Exception("Could not open file: $remote_file");
$data_to_send = @file_get_contents($local_file);
if ($data_to_send === false)
throw new Exception("Could not open local file: $local_file.");
if (@fwrite($stream, $data_to_send) === false)
throw new Exception("Could not send data from file: $local_file.");
@fclose($stream);
}
public function __destruct()
{
$this->connection = null;
// try{
// @ssh2_exec($this->connection, 'exit');
// }catch(Exception $e) {
// Log::warning($e->getMessage());
// }
}
}