<?php
/**
* 測試sftp 連接及下載遠程文件
*/
$config = [
'host' => '192.168.1.111',
'username'=>'root',
'password'=>'',
'port'=>'22',
];
$localPath = 'D:\\jaja\\php1\\';//本地存儲路徑
$remotePath = '/data/data/';
$sftp = new Sftp($config);
$re = $sftp->ssh2_dir_exits($remotePath);
if($re) {
$fileArr = $sftp->fileList($remotePath);
if(!$fileArr) {
printLog('遠程目錄獲取文件列表失敗 或者 遠程目錄爲空');exit;
}
foreach ($fileArr as $k => $v) {
$downRes = $sftp->downSftp($remotePath . '/' . $v, $localPath . '\\' . $v);
if(!$downRes) {
printLog('下載文件失敗---' . $v);
} else {
printLog('下載文件成功---' . $v);
sleep(1);
$delRes = $sftp->deleteSftp($remotePath . '/' . $v);
if(!$delRes) {
printLog('刪除文件失敗---' . $v);
} else {
printLog('刪除文件成功---' . $v);
}
}
}
sleep(1);
$upRes = $sftp->upSftp($localPath . '112233.html', $remotePath . '123.html');
if(!$upRes) {
printLog('上傳文件失敗---112233.html');
} else {
printLog('上傳文件成功---112233.html');
}
} else {
printLog('訪問遠程目錄不存在');exit;
}
class Sftp
{
// 初始配置爲NULL
private $config = NULL;
// 連接爲NULL
private $conn = NULL;
//sftp resource
private $ressftp = NULL;
// 初始化
public function __construct($config)
{
$this->config = $config;
$this->connect();
}
public function connect()
{
$this->conn = ssh2_connect($this->config['host'], $this->config['port']);
if( ssh2_auth_password($this->conn, $this->config['username'], $this->config['password'])) {
$this->ressftp = ssh2_sftp($this->conn);//啓動引力傳動系統
}else{
printLog("用戶名或密碼錯誤");exit();
}
}
/**
* 判段遠程目錄是否存在
* @param $dir /遠程目錄
* @return bool
*/
public function ssh2_dir_exits($dir){
return file_exists("ssh2.sftp://" . intval($this->ressftp) .$dir);
}
/**
* 下載文件
* @param $remote /遠程文件地址
* @param $local /下載到本地的地址
* @return bool
*/
public function downSftp($remote, $local)
{
return copy("ssh2.sftp://" . intval($this->ressftp).$remote, $local);
}
/**
* 文件上傳
* @param $local /本地文件地址
* @param $remote /上傳後的文件地址
* @param int $file_mode
* @return bool
*/
public function upSftp($local,$remote, $file_mode = 0777)
{
return copy($local, "ssh2.sftp://" . intval($this->ressftp) . $remote);
}
/**
* 刪除遠程目錄中文件
* @param $file
* @return bool
*/
public function deleteSftp($file)
{
return ssh2_sftp_unlink($this->ressftp, $file);
}
/**
* 遍歷遠程目錄
* @param $remotePath
* @return array
*/
public function fileList($remotePath)
{
$fileArr = scandir('ssh2.sftp://' . intval($this->ressftp) . $remotePath);
foreach ($fileArr as $k => $v) {
if($v == '.' || $v == '..') {
unset($fileArr[$k]);
}
}
return $fileArr;
}
}
function printLog($log)
{
echo '[' . date('Y-m-d H:i:s', time()) . '] - ' . $log . "<br>";
}
參考: