Files not uploading to remote server with Net_SFTP

久未见 提交于 2019-12-02 14:22:56

问题


I have the following class for uploading files in a directory, however, the first directory that should be created is getting set up as 'File' rather then a 'File Folder'. Because of that, the items that should be uploaded are not uploading properly. I'm not sure if I am missing a step or not or if I set this up incorrectly.

include 'Net/SFTP.php';

class SFTPConnection
{
    private $sftp;

    public function __construct($host, $username, $password)
    {
        $this->sftp = new Net_SFTP($host);
        if (!$this->sftp)
            error_log("Could not connect to $host.");

        if (!$this->sftp->login($username, $password))
            error_log("Could not authenticate with username $username " .
              "and password $password.");
    }

    public function uploadFiles($dir, $to, $from) {
        $result = array();
        $toDir = str_replace($from, $to, $dir);
        $cdir = scandir($dir);

        foreach ($cdir as $key => $value) {
            if (!in_array($value, array(".", ".."))) {
                if (is_dir($dir . DIRECTORY_SEPARATOR . $value)) {
                    if(!$this->sftp->mkdir($toDir . DIRECTORY_SEPARATOR .$value)) {
                        echo "Could not create directory <br>'";
                        exit();
                    }
                    $result[$value] = $this->uploadFiles($dir . DIRECTORY_SEPARATOR . $value, $to, $from);
                } else {
                    $result[] = $value;
                    echo "Uploading $dir/$value <br>";
                    if(!$this->sftp->put($toDir . DIRECTORY_SEPARATOR . $value, $dir . DIRECTORY_SEPARATOR . $value, NET_SFTP_LOCAL_FILE)) {
                        echo "Could not upload file <br>";
                        exit();
                    }
                }
            }
        }
        return $result;
    }
}

回答1:


It works for me. I tried $sftp->mkdir('Test folder') and $sftp->mkdir('./Test folder/Another folder'). The directories that were created were created as expected.

One thing to keep in mind... DIRECTORY_SEPARATOR is probably not the best thing to use in this instance. On Windows, for example, DIRECTORY_SEPARATOR is \ - not /. This is an issue because the SFTP specs say that directories are to be represented with / - not . Quoting draft-ietf-secsh-filexfer-02:

This protocol represents file names as strings. File names are assumed to use the slash ('/') character as a directory separator.

I guess to have further insight a copy of the SFTP logs would be helpful. Maybe just provide the SFTP logs of a mkdir operation. You can get the SFTP logs by doing define('NET_SFTP_LOGGING', 2) at the top and then doing echo $sftp->getSFTPLog() after the mkdir.



来源:https://stackoverflow.com/questions/38361843/files-not-uploading-to-remote-server-with-net-sftp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!