Dashboard
PHP Cách download files từ một server sftp về local
<?php
// Make our connection
$connection = ssh2_connect('c0389i0.hondacars.biz');
// Authenticate
if (!ssh2_auth_password($connection, 'skkikaku', 'lG17DwToDvi')) {
throw new Exception('Unable to connect.');
} else {
echo "connected";
}
// Create our SFTP resource
if (!$sftp = ssh2_sftp($connection)) {
throw new Exception('Unable to create SFTP connection.');
} else {
echo "connected2";
}
$files = array();
$dirHandle = opendir("ssh2.sftp://$sftp/home/skkikaku/csv/");
// Properly scan through the directory for files, ignoring directory indexes (. & ..)
while (false !== ($file = readdir($dirHandle))) {
if ($file != '.' && $file != '..') {
$files[] = $file;
}
}
if (count($files)) {
foreach ($files as $fileName) {
// Remote stream
if (!$remoteStream = @fopen("ssh2.sftp://$sftp/home/skkikaku/csv/$fileName", 'r')) {
throw new Exception("Unable to open remote file: $fileName");
}
// Local stream
chmod($_SERVER['DOCUMENT_ROOT'] . '/localdir/$fileName', 0777);
if (!$localStream = @fopen($_SERVER['DOCUMENT_ROOT']."/localdir/$fileName", 'w')) {
throw new Exception("Unable to open local file for writing: /localdir/$fileName");
}
// Write from our remote stream to our local stream
$read = 0;
$fileSize = filesize("ssh2.sftp://$sftp/home/skkikaku/csv/$fileName");
while ($read < $fileSize && ($buffer = fread($remoteStream, $fileSize - $read))) {
// Increase our bytes read
$read += strlen($buffer);
// Write to our local file
if (fwrite($localStream, $buffer) === FALSE) {
throw new Exception("Unable to write to local file: /localdir/$fileName");
}
}
// Close our streams
fclose($localStream);
fclose($remoteStream);
}
}
Source: https://viblo.asia/p/php-cach-download-files-tu-mot-server-sftp-ve-local-gDVK2oVrZLj