php如何实现sftp上传

发布时间:2021-09-14 11:29:11 作者:chen
来源:亿速云 阅读:109

这篇文章主要讲解了“php如何实现sftp上传”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“php如何实现sftp上传”吧!

本文操作环境: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 = @ssh3_connect($host, $port);
        if (! $this->connection)
            throw new Exception("Could not connect to $host on port $port.");
    }

    public function login($username, $password)
    {
        if (! @ssh3_auth_password($this->connection, $username, $password))
            throw new Exception("Could not authenticate with username $username " .
                                "and password $password.");

        $this->sftp = @ssh3_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("ssh3.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("ssh3.sftp://$sftp$remote_file", 'w');

fopen的时候 执行文件 会报 "Segmentation fault" 的错误, 然后变成以下方式便可以解决

$stream = @fopen("ssh3.sftp://" . intval($sftp) . $remote_file, 'w');

其中,在实现sftp上传的时候,没有在意上传文件和上传目录的区别(例如: /upload 和 /upload/test.txt 的问题), 导致每次执行php 都会报 fopen(): Unable to open ssh3.sftp://5/upload on remote host. 问题解决方法就是 认真, 大写的认真

以上就是php做的, 只要登录sftp服务器 进行查看便知道结果.

sftp 命令登录方式:

sftp -oPort=port  user@server 然后输入密码, 进去之后可以到相对的目录查看文件是否存在.

感谢各位的阅读,以上就是“php如何实现sftp上传”的内容了,经过本文的学习后,相信大家对php如何实现sftp上传这一问题有了更深刻的体会,具体使用情况还需要大家实践验证。这里是亿速云,小编将为大家推送更多相关知识点的文章,欢迎关注!

推荐阅读:
  1. sublime使用sftp上传文件
  2. PHP-sftp文件上传

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

php

上一篇:html5如何自定义audio

下一篇:php设置cookie记住密码的方法

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》