I need to fetch some files from the root directory of a distant server through ssh, the local machine uses php7. I've made this script:
<?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;
It works, i.e. the files are fetched, but the script never stops.
If I knew the name of the file to fetch, the script would then be:
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);
}
and then the file is fetch and the script stops at the end of its execution.
I cannot use phpseclib as it requires composer and I can't use it on the locale machine.
What can I do to opendir()
and readdir()
without having the script running infinitely?
try to break after your file_put_contents
for example:
if (file_put_contents('/path/to/dir/' . $file, $strData) !== false) {
break;
}
or as a best approach you may use closedir
directly after putting your data
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);