我无法通过SFTP上传文件,但我可以下载文件吗?最后,我将不得不通过SFTP将文件发送到另一个SFTP位置,然后我正在上传到。我有权在我的测试环境中的所有文件夹中写入,我目前正在收到错误。我写的目录有777作为权利。
服务器正在使用PHP7.0。
我的代码可以连接到SFTP并登录。
protected $connection;
protected $sftp;
public function __construct($server,$username,$pass){
$port=22;
$this->connection = @ssh2_connect($server, $port);
if (!$this->connection){
throw new Exception("Could not connect to ".$server." on port".$port.".");
} else {
$this->login($username,$pass);
}
}
public function login($username, $password){
if (! @ssh2_auth_password($this->connection, $username, $password)){
throw new Exception("Could not authenticate with username ".$username);
}
$this->sftp = @ssh2_sftp($this->connection);
if(!$this->sftp){
throw new Exception("Could not initialize SFTP subsystem.");
}
}
以下是上传文件的功能。当我使用ssh2_scp_send($ sftp,$ local_file,$ remote_file,0644)时;我收到错误:
警告:ssh2_scp_send():创建远程文件失败: (null)在 /var/www/html/scripts/class.sftp.php 上线 45
当我使用@fopen(“ssh2.sftp:// $ sftp $ remote_file”,'w')时; 我收到错误:
无法打开文件:$ remote_file。
public function uploadFile($local_file, $remote_file){
$sftp = $this->connection;
try{
ssh2_scp_send($sftp, $local_file, $remote_file, 0644);
ssh2_exec($sftp, 'exit');
return true;
}catch(Exception $oErr) {
print __CLASS__ . ", method uploadFile (in class.sftp van SAN) foutmelding:\n"
. " regel ". $oErr->getLine() . ": " . $oErr->getMessage() ."\n ";
}
/*try{
$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);
}catch(Exception $oErr) {
print __CLASS__ . ", method uploadFile (in class.sftp van SAN) foutmelding:\n"
. " regel ". $oErr->getLine() . ": " . $oErr->getMessage() ."\n ";
}*/
这是下载功能,没有问题。
public function getFile($local_file,$remote_file){
$sftp = $this->connection;
ssh2_scp_recv($sftp, $remote_file, $local_file);
return true;
}
下载适用于ssh2_scp_recv,但不适用于fopen。所以我希望ssh2_scp_send能够正常工作。
public function getFile($local_file,$remote_file){
/*$stream = @fopen("ssh2.sftp://$sftp$remote_file", 'r');
if(!$stream){
return false;
throw new Exception("Could not open file: $remote_file");
}
$size = $this->getFileSize($remote_file);
$contents = '';
$read = 0;
$len = $size;
while ($read < $len && ($buf = fread($stream, $len - $read))) {
$read += strlen($buf);
$contents .= $buf;
}
file_put_contents($local_file, $contents);
@fclose($stream);*/
}