Last active
February 7, 2021 04:23
-
-
Save sikofitt/667d8e19015b4af8306ef66573120dec to your computer and use it in GitHub Desktop.
Example of using the ssh2.sftp:// stream from the ssh2 pecl extension
This file contains 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 declare(strict_types=1); | |
// Tested on | |
// PHP 7.4.14 (cli) (built: Jan 5 2021 15:12:29) ( ZTS Visual C++ 2017 x64 ) | |
// Windows 10 Pro | |
// pecl ssh2 v1.2 | |
// Remote server | |
// Gentoo GNU/Linux Base System release 2.7 | |
error_reporting(E_ALL); | |
ini_set('display_errors', '1'); | |
file_put_contents(__DIR__.'/sftp.test', 'worked!'); | |
$host = '10.5.6.254'; | |
$port = 22; | |
$connection = ssh2_connect($host, $port); | |
if(!is_resource($connection)) { | |
throw new Exception('Connection failed.'); | |
} | |
// Without the __DIR__ php will just try to get 'id_rsa' and will fail. | |
// if your keys are elsewhere __DIR__ should be changed to C:\path\to\your\files | |
$privateKey = __DIR__.'\id_rsa_test'; // id_rsa | |
$publicKey = __DIR__.'\id_rsa_test.pub'; // id_rsa.pub | |
$username = 'eric'; | |
$passphrase = 'passphrase'; // set this to passphrase if you have one. | |
$errorHandler = static function( | |
int $errorNumber, | |
string $errorString, | |
string $errorFile = '', | |
int $errorLine = 0, | |
array $errorContext = [] | |
) use($connection) { | |
ssh2_disconnect($connection); | |
var_dump($errorContext); | |
throw new ErrorException($errorString, $errorNumber, 1, $errorFile, $errorLine); | |
}; | |
set_error_handler($errorHandler); | |
if(false === ssh2_auth_pubkey_file($connection, $username, $publicKey, $privateKey, $passphrase)) { | |
throw new Exception('Authentication failed.'); | |
} | |
$sftp = ssh2_sftp($connection); | |
$remoteFile = '/home/eric/sftp.test'; | |
$streamUrl = sprintf('ssh2.sftp://%d%s', (int)$sftp, $remoteFile); | |
$localFile = __DIR__ . '/sftp.test'; | |
if(!file_exists($streamUrl)) { | |
if(true === copy($localFile, $streamUrl)) { | |
print sprintf('Successfully copied local file "%s" to remote file "%s"', $localFile, $streamUrl) . PHP_EOL; | |
} else { | |
print sprintf('Failed to copy local file %s to remote file %s', $localFile, $streamUrl) . PHP_EOL; | |
} | |
} else { | |
print sprintf('File %s exists.', $streamUrl) . PHP_EOL; | |
} | |
ssh2_disconnect($sftp); | |
ssh2_disconnect($connection); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment