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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值