Upload file sftp php

php sec lib: SFTP Examples and Notes

stat() and lstat() return associative arrays with misc information about the files. lstat() and stat() are identical with the caveat that when the file in question is a symbolic link the information returned refers to the link itself and not the file (or directory) being linked to.

size() returns the ‘size’ index of the associative array returned by lstat()

Uploading files

The function definition for put() is as follows:

function put($remote_file, $data, $mode = NET_SFTP_STRING, $start = -1, $local_start = -1)

Uploading strings vs. files

$sftp->put(‘filename.remote’, ‘filename.local’) creates filename.remote on the remote server with ‘filename.local’ as the contents.

$sftp->put(‘filename.remote’, ‘xxx’, NET_SFTP_LOCAL_FILE) creates filename.remote on the remote server such that the contents of it and filename.local match. ie. with NET_SFTP_LOCAL_FILE it uploads a file and without it it uploads a string.

$sftp->put(‘filename.remote’, ‘xxx’, NET_SFTP_RESUME) will append ‘xxx’ to filename.remote.

$sftp->put(‘filename.remote’, ‘filename.local’, NET_SFTP_LOCAL_FILE | NET_SFTP_RESUME_START) will append filename.remote to filename.local.

$sftp->put(‘filename.remote’, ‘filename.local’, NET_SFTP_LOCAL_FILE | NET_SFTP_RESUME) will append all but the first $sftp->size(‘filename.remote’) bytes of filename.local to filename.remote. The idea being that if your transfer is interupted you can restart it.

$start and $local_start give you more fine grained control over this process and take precident over NET_SFTP_RESUME when they’re non-negative. ie. $start could let you write at the end of a file (like NET_SFTP_RESUME) or in the middle of one. $local_start could let you start your reading from the end of a file (like NET_SFTP_RESUME_START) or in the middle of one.

Downloading files

The function definition for get() is as follows:

function get($remote_file, $local_file = false, $offset = 0, $length = -1)

Returns a string containing the contents of $remote_file if $local_file is left undefined or a boolean false if the operation was unsuccessful. If $local_file is defined, returns true or false depending on the success of the operation.

Источник

ssh2_sftp

Запрашивает подсистему SFTP из уже открытого соединения SSH2.

Список параметров

Идентификатор соединения SSH, полученный из ssh2_connect() .

Возвращаемые значения

Этот метод возвращает ресурс SSH2 SFTP для использования в остальных функциях ssh2_sftp_*() и обёртке ssh2.sftp:// для fopen или false в случае возникновения ошибки.

Примеры

Пример #1 Открытие файла через SFTP

$connection = ssh2_connect ( ‘shell.example.com’ , 22 );
ssh2_auth_password ( $connection , ‘username’ , ‘password’ );

$sftp = ssh2_sftp ( $connection );

$stream = fopen ( ‘ssh2.sftp://’ . intval ( $sftp ) . ‘/path/to/file’ , ‘r’ );
?>

Смотрите также

User Contributed Notes 13 notes

Here is an example of how to send a file with SFTP:

Читайте также:  Php if strings not equal

class SFTPConnection
private $connection ;
private $sftp ;

public function __construct ( $host , $port = 22 )
$this -> connection = @ ssh2_connect ( $host , $port );
if (! $this -> connection )
throw new Exception ( «Could not connect to $host on port $port .» );
>

public function login ( $username , $password )
if (! @ ssh2_auth_password ( $this -> connection , $username , $password ))
throw new Exception ( «Could not authenticate with username $username » .
«and password $password .» );

$this -> sftp = @ ssh2_sftp ( $this -> connection );
if (! $this -> sftp )
throw new Exception ( «Could not initialize SFTP subsystem.» );
>

public function uploadFile ( $local_file , $remote_file )
$sftp = $this -> sftp ;
$stream = @ fopen ( «ssh2.sftp:// $sftp$remote_file » , ‘w’ );

if (! $stream )
throw new Exception ( «Could not open file: $remote_file » );

$data_to_send = @ file_get_contents ( $local_file );
if ( $data_to_send === false )
throw new Exception ( «Could not open local file: $local_file .» );

if (@ fwrite ( $stream , $data_to_send ) === false )
throw new Exception ( «Could not send data from file: $local_file .» );

try
$sftp = new SFTPConnection ( «localhost» , 22 );
$sftp -> login ( «username» , «password» );
$sftp -> uploadFile ( «/tmp/to_be_sent» , «/tmp/to_be_received» );
>
catch ( Exception $e )
echo $e -> getMessage () . «\n» ;
>

Note that you must enter the full wrapper URI order for functions that accept those parameters to work properly. For example, this (which is referenced more than once in other comments) does not work:

while (false !== ($file = readdir($handle))) if (is_dir($file)) < /* . */ >

$sc = ssh2_sftp(. );
while (false !== ($file = readdir($handle))) if (is_dir(«ssh2.sftp://$sc/$file»)) < /* . */ >

You need to pass the «path» into these functions as an fopen() wrapper URI.

I added some functionality for scanning the filesystem and receiving and deleting files.

class SFTPConnection
private $connection;
private $sftp;

public function __construct($host, $port=22)
$this->connection = @ssh2_connect($host, $port);
if (! $this->connection)
throw new Exception(«Could not connect to $host on port $port.»);
>

public function login($username, $password)
if (! @ssh2_auth_password($this->connection, $username, $password))
throw new Exception(«Could not authenticate with username $username » . «and password $password.»);
$this->sftp = @ssh2_sftp($this->connection);
if (! $this->sftp)
throw new Exception(«Could not initialize SFTP subsystem.»);
>

public function uploadFile($local_file, $remote_file)
$sftp = $this->sftp;
$stream = @fopen(«ssh2.sftp://$sftp$remote_file», ‘w’);
if (! $stream)
throw new Exception(«Could not open file: $remote_file»);
$data_to_send = @file_get_contents($local_file);
if ($data_to_send === false)
throw new Exception(«Could not open local file: $local_file.»);
if (@fwrite($stream, $data_to_send) === false)
throw new Exception(«Could not send data from file: $local_file.»);
@fclose($stream);
>

public function receiveFile($remote_file, $local_file)
$sftp = $this->sftp;
$stream = @fopen(«ssh2.sftp://$sftp$remote_file», ‘r’);
if (! $stream)
throw new Exception(«Could not open file: $remote_file»);
$contents = fread($stream, filesize(«ssh2.sftp://$sftp$remote_file»));
file_put_contents ($local_file, $contents);
@fclose($stream);
>

Читайте также:  Php url до скрипта

public function deleteFile($remote_file) $sftp = $this->sftp;
unlink(«ssh2.sftp://$sftp$remote_file»);
>
>

The sftp class provided by David Barnes works great. However, if you get errors about fopen and it failing to open a stream, try the fully qualified path on the remote server.

For example, if you are uploading a file to /Users/username/Sites/file.txt this may not work:

try $sftp = new SFTPConnection ( «localhost» , 22 );
$sftp -> login ( «username» , «password» );
$sftp -> uploadFile ( «/tmp/to_be_sent» , «Sites/file.txt» );
>
catch ( Exception $e ) echo $e -> getMessage () . «\n» ;
>
?>

but this will:

try $sftp = new SFTPConnection ( «localhost» , 22 );
$sftp -> login ( «username» , «password» );
$sftp -> uploadFile ( «/tmp/to_be_sent» , «/Users/username/Sites/file.txt» );
>
catch ( Exception $e ) echo $e -> getMessage () . «\n» ;
>
?>

Don’t assume that since you are connecting as that user that you are starting in its home space.

Another possible option is that you need to use http://us.php.net/manual/en/function.ssh2-sftp-mkdir.php first to make the directory if it does not exist already, and then upload the file into it.

Adding a function to previous class to connect with key instead of user/password

public function loginWithKey ( $username , $publicKey , $privateKey , $passphrase = null )
if (!@ ssh2_auth_pubkey_file ( $this -> connection , $username , $publicKey , $privateKey , $passphrase )) throw new Exception ( «Could not authenticate with given keys or passphrase» );
>

$this -> sftp = @ ssh2_sftp ( $this -> connection );
if (! $this -> sftp ) throw new Exception ( «Could not initialize SFTP subsystem.» );
>
>

Here is a modified SFTPConnection class previously posted that returns a recursive directory scanFilesystem method.

class SFTPConnection
private $connection ;
private $sftp ;

public function __construct ( $host , $port = 22 )
$this -> connection = @ ssh2_connect ( $host , $port );
if (! $this -> connection )
throw new Exception ( «Could not connect to $host on port $port .» );
>

public function login ( $username , $password )
if (! @ ssh2_auth_password ( $this -> connection , $username , $password ))
throw new Exception ( «Could not authenticate with username $username » . «and password $password .» );
$this -> sftp = @ ssh2_sftp ( $this -> connection );
if (! $this -> sftp )
throw new Exception ( «Could not initialize SFTP subsystem.» );
>

public function uploadFile ( $local_file , $remote_file )
$sftp = $this -> sftp ;
$stream = @ fopen ( «ssh2.sftp:// $sftp$remote_file » , ‘w’ );
if (! $stream )
throw new Exception ( «Could not open file: $remote_file » );
$data_to_send = @ file_get_contents ( $local_file );
if ( $data_to_send === false )
throw new Exception ( «Could not open local file: $local_file .» );
if (@ fwrite ( $stream , $data_to_send ) === false )
throw new Exception ( «Could not send data from file: $local_file .» );
@ fclose ( $stream );
>

Читайте также:  Intellij idea javascript plugin

function scanFilesystem ( $remote_file ) $sftp = $this -> sftp ;
$dir = «ssh2.sftp:// $sftp$remote_file » ;
$tempArray = array();

if ( is_dir ( $dir )) if ( $dh = opendir ( $dir )) while (( $file = readdir ( $dh )) !== false ) $filetype = filetype ( $dir . $file );
if( $filetype == «dir» ) $tmp = $this -> scanFilesystem ( $remote_file . $file . «/» );
foreach( $tmp as $t ) $tempArray [] = $file . «/» . $t ;
>
> else $tempArray [] = $file ;
>
>
closedir ( $dh );
>
>

public function receiveFile ( $remote_file , $local_file )
$sftp = $this -> sftp ;
$stream = @ fopen ( «ssh2.sftp:// $sftp$remote_file » , ‘r’ );
if (! $stream )
throw new Exception ( «Could not open file: $remote_file » );
$contents = fread ( $stream , filesize ( «ssh2.sftp:// $sftp$remote_file » ));
file_put_contents ( $local_file , $contents );
@ fclose ( $stream );
>

public function deleteFile ( $remote_file ) $sftp = $this -> sftp ;
unlink ( «ssh2.sftp:// $sftp$remote_file » );
>
>
?>

I changed the read function to:

public function receiveFile($remote_file, $local_file)
$sftp = $this->sftp;
$stream = @fopen(«ssh2.sftp://$sftp$remote_file», ‘r’);
if (! $stream)
throw new Exception(«Could not open file: $remote_file»);
$size = $this->getFileSize($remote_file);
$contents = »;
$read = 0;
$len = $size;
while ($read < $len && ($buf = fread($stream, $len - $read))) $read += strlen($buf);
$contents .= $buf;
>
file_put_contents ($local_file, $contents);
@fclose($stream);
>

public function getFileSize($file) $sftp = $this->sftp;
return filesize(«ssh2.sftp://$sftp$file»);
>

When uploading (writing) a file you must use an absolute path, not a relative one.

If, like me, you want to use a relative path, you can use the following code:

Источник

Uploading files with SFTP

To upload files using SFTP (Secure File Transfer Protocol) in PHP, you can use the SSH2 extension, which allows you to connect to an SFTP server and perform various operations such as uploading, downloading, and deleting files. Here is an example of how you can use the SSH2 extension to upload a file to an SFTP server:

 $connection = ssh2_connect('example.com', 22); ssh2_auth_password($connection, 'username', 'password'); $sftp = ssh2_sftp($connection); $file = '/path/to/local/file.txt'; $remote_file = '/path/to/remote/file.txt'; ssh2_scp_send($connection, $file, $remote_file, 0644); ?>

This example first establishes a connection to the SFTP server using the ssh2_connect function, and then authenticates with a username and password using the ssh2_auth_password function. Next, it opens an SFTP session using the ssh2_sftp function and then uses the ssh2_scp_send function to upload the file.

Alternatively, you can use other libraries like phpseclib, which provides an SFTP implementation in pure PHP.

 include 'Net/SFTP.php'; $sftp = new Net_SFTP('example.com'); if (!$sftp->login('username', 'password')) < exit('Login Failed'); > $local_file = '/path/to/local/file.txt'; $remote_file = '/path/to/remote/file.txt'; $sftp->put($remote_file, $local_file, NET_SFTP_LOCAL_FILE); ?>

Please note that these are just examples and actual implementation might change depending on your requirements.

Источник

Оцените статью