问题
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