通过SSH2检索远程文件适用于PHP 7,但不适用于PHP5.6

时间:2017-08-11 04:14:57

标签: php ssh2-sftp

所以..这个函数在PHP7中运行得很好..但我必须将服务器缩减到5.6,因为其他一些代码不适用于PHP7。

一旦服务器缩减回5.6,此SSH2函数将抛出无法打开目录错误。 我检查了所有被调用的函数,它们都是PHP 4.0及更高版本。有人有什么想法吗?

    function get_the_k12_file($filename)
 {
$host = "thehost.com";
$port = 22;
$username = "username!";
$password = "password!";
$remoteDir = "/the/path/tothefile/";
$localDir = "";
  
if (!function_exists("ssh2_connect"))
    die("Function ssh2_connect does not exist.");
  
if (!$connection = ssh2_connect($host, $port))
    die("Failed to connect.");
  
if (!ssh2_auth_password($connection, $username, $password))
    die("Failed to authenticate.");
  
if (!$sftp_conn = ssh2_sftp($connection))
    die("Failed to create a sftp connection.");
  
if (!$dir = opendir("ssh2.sftp://$sftp_conn$remoteDir"))
    die("Failed to open the directory.");
  
$files = array();
while ( ($file = readdir($dir)) !== false)
{
    if(substr($file, -4)==".zip")
    {
        $files[]=$file;
    }
}
closedir($dir);
  
foreach ($files as $file)
{
 
if($file==$filename)
  {
    echo "Copying file: $file\n";
    if (!$remote = fopen("ssh2.sftp://$sftp_conn$remoteDir$file", "r"))
    {
        echo "Failed to open remote file: $file\n";
        continue;
    }
  
    if (!$local = fopen($localDir . $file, "w"))
    {
        echo "Failed to create local file: $file\n";
        continue;
    }
  
    $read = 0;
    $filesize = filesize("ssh2.sftp://$sftp_conn/$remoteDir$file");


    while ( ($read < $filesize) && ($buffer = fread($remote, $filesize - $read)) )
    {
        $read += strlen($buffer);
        if (fwrite($local, $buffer) === FALSE)
        {
            echo "Failed to write to local file: $file\n";
            break;
        }
    }
 
   }
    fclose($local);
    fclose($remote);
}
}

0 个答案:

没有答案