sftp上传到远程服务器

开发遇到一个需求,需要将图片通过sftp上传到远程服务器上,之前没用过这个功能,折腾了我好几天才搞定,下面记录下我的处理方法:

$sftp = 'ssh2.sftp://';
//连接sftp
$conn = ssh2_connect('IP','端口');
//登录 ssh2_auth_password(
$conn,"user","password"); $result = ssh2_sftp($conn);
//判断是否存在目录HM(特别注意账号登录进来后默认的文件路径是不是根目录,否则找不到文件夹,也不能创建文件夹,可通过pwd命令查看当前文件夹路径
if (!file_exists($sftp.$result.'/HM/')) {   $dir = ssh2_sftp_mkdir($result, '/HM/',0777,true); }else{   $dir = true; } if($dir){   //realpath方法将相对路径转为绝对路径   $send = ssh2_scp_send($conn,realpath($localfile),$remotefile);
  //开始这种方法是测试可行的,后来ftp账号权限被修改,导致进不到根目录,然后不知为什么就不行了,之后就只能曲线救国采用下面的方法
}else{   $send = false; }
//远程服务器创建一个文件
$sftpStream
= fopen($sftp.$result.$remotefilename, 'w'); //若报(failed to open stream: operation failed)错误,需要将$result改为intval($result)
//获取本地文件
$data_to_send = file_get_contents(realpath($localfilename));
//将本地文件写入到远程文件中
$send = fwrite($sftpStream, $data_to_send);
//关闭文件流
fclose($sftpStream);
linux下命令行连接sftp

sftp -oPort=22 username@ip
原文地址:https://www.cnblogs.com/dreamydeng/p/6806384.html