太忙,流程分析待补
代码来源:https://randomdrake.com/2012/02/08/listing-and-downloading-files-over-sftp-with-php-and-ssh2/
[code lang="php"]<?php
// Make our connection
$connection = ssh2_connect('ftp.somehost.com');
// Authenticate
if (!ssh2_auth_password($connection, 'username', 'password'))
throw new Exception('Unable to connect.');
// Create our SFTP resource
if (!$sftp = ssh2_sftp($connection))
throw new Exception('Unable to create SFTP connection.');
/**
* Now that we have our SFTP resource, we can open a directory resource
* to get us a list of files. Here we will use the $sftp resource in
* our address string as I previously mentioned since our ssh2://
* protocol allows it.
*/
$files = array();
$dirHandle = opendir("ssh2.sftp://$sftp/");
// Properly scan through the directory for files, ignoring directory indexes (. & ..)
while (false !== ($file = readdir($dirHandle)))
if ($file != '.' && $file != '..')
$files[] = $file;
/**
* Using our newly created list of files, we can go about downloading. We will
* open a remote stream and a local stream and write from one to the other.
* We will use error suppression on the fopen call to suppress warnings from
* not being able to open the file.
*/
if (count($files))
foreach ($files as $fileName)
// Remote stream
if (!$remoteStream = @fopen("ssh2.sftp://$sftp/$fileName", 'r'))
throw new Exception("Unable to open remote file: $fileName");
// Local stream
if (!$localStream = @fopen("/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/$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);
[/code]
没有评论:
发表评论