2017-03-20 69 views
0

我需要通過ssh從遠程服務器的根目錄中獲取一些文件,本地機器使用php7。我已經做了這個腳本:在ssh2 opendir永不停止

<?php 
$strServer = "my-server.com"; 
$strServerPort = "22"; 
$strServerUsername = "my.username"; 
$strServerPassword = "my-password"; 
$resConnection = ssh2_connect($strServer, $strServerPort); 
if(ssh2_auth_password($resConnection, $strServerUsername, $strServerPassword)) { 
    $files = array(); 
    $resSFTP = ssh2_sftp($resConnection); 
    $dirHandle = opendir("ssh2.sftp://" . intval($resSFTP) . "/"); 
    while ($dirHandle && ($file = readdir($dirHandle)) !== false) { 
     if ($file == "." || $file == "..") { 
      continue; 
     } 
     $strData = file_get_contents("ssh2.sftp://" . intval($resSFTP) . "/" . $file); 
     file_put_contents('/path/to/dir/' . $file, $strData); 
    } 
    ssh2_exec($resConnection, 'exit'); 
    unset($resConnection); 
} 

die; 

它的工作原理,即文件被提取,但腳本永不停止。
如果我知道,以獲取文件的名稱,該腳本將被:

if(ssh2_auth_password($resConnection, $strServerUsername, $strServerPassword)) { 
    $files = array(); 
    $resSFTP = ssh2_sftp($resConnection); 
    $file = 'name_of_the_file.xlsx'; 
    $strData = file_get_contents("ssh2.sftp://" . intval($resSFTP) . "/" . $file); 
    file_put_contents('/path/to/dir/' . $file, $strData); 
} 

,然後將文件提取是和腳本在其執行結束時停止。

我不能使用phpseclib,因爲它需要作曲家,我不能在語言環境機器上使用它。

如何讓opendir()readdir()沒有腳本無限運行?

回答

1

試試你file_put_contents

後打破例如:

if (file_put_contents('/path/to/dir/' . $file, $strData) !== false) { 
    break; 
} 

或作爲最好的方法,你可以把你的數據

do { 
    if ($file == "." || $file == "..") { 
     continue; 
    } 
    $strData = file_get_contents("ssh2.sftp://" . intval($resSFTP) . "/" . $file); 
    if (file_put_contents('/path/to/dir/' . $file, $strData)) { 
     break; 
    } 
} while ($dirHandle && ($file = readdir($dirHandle)) !== false); 

closedir($dirHandle); 
+0

後直接使用closedir'closedir'肯定的是要走的路,但如果我把它放在'while'裏面,只有第一個文件被提取。如果我在'while'之後放置所有文件,並且腳本停止。如果你可以編輯你的答案,以整合,我會接受它。非常感謝。 – OSdave

+0

所以你在環路外對接可以解決它嗎?但是如果你需要用另一種方法做同樣的事情,你可以對文件進行計數,如果索引等於計數,則關閉dir; – hassan

+0

是的,循環外的'closedir'對我來說是正常的,正是我需要的:) – OSdave