php怎么实现sftp上传
时间:2021-09-22 来源:互联网
今天PHP爱好者给大家带来php实现sftp上传的方法:1、创建代码“class SFTPConnection private $connection...try{...}catch{...}”;2、执行“sftp -oPort=port user@server”。
本文操作环境:windows7系统、PHP7.1版,DELL G3电脑
php怎么实现sftp上传?
php 实现SFTP上传文件
php 实现sftp文件上传完全可以用php.net 官网中的方式,代码如下:
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($username, $password)
{
if (! @ssh2_auth_password($this->connection, $username, $password))
throw new Exception("Could not authenticate with username $username " .
"and password $password.");
$this->sftp = @ssh2_sftp($this->connection);
if (! $this->sftp)
throw new Exception("Could not initialize SFTP subsystem.");
}
public function uploadFile($local_file, $remote_file)
{
$sftp = $this->sftp;
$stream = @fopen("ssh2.sftp://$sftp$remote_file", 'w');
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);
}
}
try
{
$sftp = new SFTPConnection("localhost", 22);
$sftp->login("username", "password");
$sftp->uploadFile("/tmp/to_be_sent", "/tmp/to_be_received");
}
catch (Exception $e)
{
echo $e->getMessage() . "\n";
}
但是在进行中遇到了一个问题, 我的php版本是 PHP 5.6.31 (cli) (built: Aug 2 2017 15:05:23) , 在执行
$stream = @fopen("ssh2.sftp://$sftp$remote_file", 'w');
fopen的时候 执行文件 会报 "Segmentation fault" 的错误, 然后变成以下方式便可以解决
$stream = @fopen("ssh2.sftp://" . intval($sftp) . $remote_file, 'w');
其中,在实现sftp上传的时候,没有在意上传文件和上传目录的区别(例如: /upload 和 /upload/test.txt 的问题), 导致每次执行php 都会报 fopen(): Unable to open ssh2.sftp://5/upload on remote host. 问题解决方法就是 认真, 大写的认真
以上就是php做的, 只要登录sftp服务器 进行查看便知道结果.
sftp 命令登录方式:
sftp -oPort=port user@server 然后输入密码, 进去之后可以到相对的目录查看文件是否存在.
以上就是php怎么实现sftp上传的详细内容,更多请关注php爱好者其它相关文章!
-
rematch推荐什么配置 rematch什么配置带的动 2025-05-30
-
幣安平台UI更新对比前后差异 2025-05-30
-
归龙潮冰雪神域26个宝箱位置详情 2025-05-30
-
污痕圣杯阿瓦隆的陨落新手怎么玩(污痕圣杯阿瓦隆陨落血湖纹章) 2025-05-30
-
原神5.1卡池新角色有谁 2025-05-30
-
污痕圣杯阿瓦隆的陨落属性和技能简单介绍(污痕圣杯阿瓦隆的陨落属性) 2025-05-30