Created
March 3, 2023 20:03
-
-
Save waqashassan98/a9dfac40dfab90904578b0cb99e7ef7c to your computer and use it in GitHub Desktop.
download a file from sftp in php
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// https://stackoverflow.com/questions/17687607/php-download-from-remote-server-via-sftp#17688779 | |
// set up SFTP server details | |
$host = ''; | |
$port = 22; | |
$username = ''; | |
$password = '; | |
$file = 'fileToDownload.csv'; | |
$remoteDir = '/complete/path/to/dir/'; | |
$localDir = 'relativepath'; | |
if (!function_exists("ssh2_connect")) | |
die('Function ssh2_connect not found, you cannot use ssh2 here'); | |
if (!$connection = ssh2_connect($host, $port)) | |
die('Unable to connect'); | |
if (!ssh2_auth_password($connection, $username, $password)) | |
die('Unable to authenticate.'); | |
if (!$stream = ssh2_sftp($connection)) | |
die('Unable to create a stream.'); | |
if (!$dir = opendir("ssh2.sftp://{$stream}{$remoteDir}")) | |
die('Could not open the directory'); | |
echo "Copying file: $file\n"; | |
if (!$remote = @fopen("ssh2.sftp://{$stream}/{$remoteDir}{$file}", 'r')) { | |
echo "Unable to open remote file: $file\n"; | |
} else { | |
if (!$local = @fopen($localDir . $file, 'w')) { | |
echo "Unable to create local file: $file\n"; | |
} else { | |
$read = 0; | |
$filesize = filesize("ssh2.sftp://{$stream}/{$remoteDir}{$file}"); | |
while ($read < $filesize && ($buffer = fread($remote, $filesize - $read))) { | |
$read += strlen($buffer); | |
if (fwrite($local, $buffer) === FALSE) { | |
echo "Unable to write to local file: $file\n"; | |
break; | |
} | |
} | |
} | |
} | |
fclose($local); | |
fclose($remote); | |
ssh2_exec($connection, 'exit'); | |
unset($connection); | |
echo "Converting File\n"; | |
$temp_output = $localDir.'output.csv'; | |
if (false !== ($ih = fopen($localDir.$file, 'r'))) { | |
$oh = fopen($temp_output, 'w'); | |
// Operations on file | |
echo "Converted\n"; | |
fclose($ih); | |
fclose($oh); | |
echo "Deleting Temporary File\n"; | |
unlink($localDir.$file); | |
echo "Renaming File\n"; | |
rename($temp_output,$localDir.$file); | |
echo "Completed"; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment