laravel Sftp 登录 检查目录 上传
-
介绍
对接第三方整的东西需要先把文件上传到他们服务器上在把地址给他们,我们这个不告诉你密码 -
配置
我是配置全放到config里了你也可以放到.env在到config
demo.php//名字你们随便整好
'wsx_pei' => '/data/111/', //我们的目录
'serverpath' => '111/111/111', //远程目录(需要上传到的目录)
'config' => [
"host" => 'file.123.cn', // sftp地址
"username" => "suibian",//用户
"port" => "20022", //端口号
"pubkey_path" => "/root/.ssh/id_rsa.pub", // 公钥的存储地址
"privkey_path" => "/root/.ssh/id_rsa.pem", // 私钥的存储地址
],
- 登录,创建目录,上传目录
不知道里面函数的去文档上看 文档
class sftpData extends Base
{
// 初始配置为NULL
public $config;
// 连接为NULL
public $conn;
//sftp resource
public $ressftp;
// 初始化
public function __construct($config)
{
parent::__construct();
$this->config = $config;
$this->connect();
}
public function connect()
{
$this->conn = ssh2_connect($this->config['host'], $this->config['port']);
$this->ressftp = ssh2_auth_pubkey_file($this->conn, $this->config['username'], $this->config['pubkey_path'],
$this->config['privkey_path']);
if ($this->ressftp) {
echo "Public Key Authentication Successful\n";
} else {
die('Public Key Authentication Failed');
}
}
// 文件上传
public function upftp($localPath_md5 = '', $local, $remote, $remote_md5 = '', $file_mode = 0644)
{
if ($local != ''){
ssh2_scp_send($this->conn,$local,$remote,$file_mode);
}
if ($localPath_md5 != ''){
ssh2_scp_send($this->conn,$localPath_md5,$remote_md5,$file_mode);
}
}
//创建目录
public function ssh2_sftp_mchkdir($path_one = '', $path_two = '', $path_three = '', $path_four = '') //使用创建目录循环
{
$sftp = ssh2_sftp($this->conn);
if ($path_one != ''){
$this->ssh2_dir_exits($path_one) == false ? ssh2_sftp_mkdir($sftp, $path_one) : '';
}
if ($path_two != '') {
$this->ssh2_dir_exits($path_two) == false ? ssh2_sftp_mkdir($sftp, $path_two) : '';
}
if ($path_three != '') {
$this->ssh2_dir_exits($path_three) == false ? ssh2_sftp_mkdir($sftp, $path_three) : '';
}
if ($path_four != '') {
$this->ssh2_dir_exits($path_four) == false ? ssh2_sftp_mkdir($sftp, $path_four) : '';
}
}
//判段目录是否存在
public function ssh2_dir_exits($dir)
{
return file_exists("ssh2.sftp://{$this->conn}" . $dir);
}