class SFTP extends SSH2 (View source)

Pure-PHP implementations of SFTP.

Constants

MASK_CONSTRUCTOR

MASK_CONNECTED

MASK_LOGIN_REQ

MASK_LOGIN

MASK_SHELL

MASK_WINDOW_ADJUST

CHANNEL_EXEC

CHANNEL_SHELL

CHANNEL_SUBSYSTEM

CHANNEL_AGENT_FORWARD

CHANNEL_KEEP_ALIVE

LOG_SIMPLE

Returns the message numbers

LOG_COMPLEX

Returns the message content

LOG_REALTIME

Outputs the content real-time

LOG_REALTIME_FILE

Dumps the content real-time to a file

LOG_MAX_SIZE

Make sure that the log never gets larger than this

READ_SIMPLE

Returns when a string matching $expect exactly is found

READ_REGEX

Returns when a string matching the regular expression $expect is found

READ_NEXT

Returns whenever a data packet is received.

Some data packets may only contain a single character so it may be necessary to call read() multiple times when using this option

CHANNEL

SFTP channel constant

\phpseclib3\Net\SSH2::exec() uses 0 and \phpseclib3\Net\SSH2::read() / \phpseclib3\Net\SSH2::write() use 1.

SOURCE_LOCAL_FILE

Reads data from a local file.

SOURCE_STRING

Reads data from a string.

SOURCE_CALLBACK

Reads data from callback: function callback($length) returns string to proceed, null for EOF

RESUME

Resumes an upload

RESUME_START

Append a local file to an already existing remote file

Properties

object $fsock The Socket Object from  SSH2
protected int $bitmap Execution Bitmap from  SSH2
protected array $server_channels Server Channels from  SSH2
protected array $channel_status Channel Status from  SSH2
protected int $window_size The Window Size from  SSH2
protected array $window_size_server_to_client Window size, server to client from  SSH2
protected $timeout Timeout from  SSH2
protected $curTimeout Current Timeout from  SSH2
protected string|false $preferred_signature_format Preferred Signature Format from  SSH2
protected array $auth Authentication Credentials from  SSH2
protected array $sortOptions Sort Options

Methods

SSH2|void
__construct(mixed $host, int $port = 22, int $timeout = 10)

Default Constructor.

static 
setCryptoEngine(int $engine)

Set Crypto Engine Mode

from  SSH2
sendIdentificationStringFirst()

Send Identification String First

from  SSH2
sendIdentificationStringLast()

Send Identification String Last

from  SSH2
sendKEXINITFirst()

Send SSH_MSG_KEXINIT First

from  SSH2
sendKEXINITLast()

Send SSH_MSG_KEXINIT Last

from  SSH2
bool
login(string $username, string|AsymmetricKey|array[]|Agent|null ...$args)

Login

bool
sublogin(string $username, string[] ...$args)

Login Helper

from  SSH2
setTimeout(mixed $timeout)

Set Timeout

from  SSH2
setKeepAlive(int $interval)

Set Keep Alive

from  SSH2
getStdError()

Get the output from stdError

from  SSH2
string
exec(string $command, callable $callback = null)

Execute Command

from  SSH2
bool
requestAgentForwarding()

Request agent forwarding of remote server

from  SSH2
string|bool|null
read(string $expect = '', int $mode = self::READ_SIMPLE)

Returns the output of an interactive shell

from  SSH2
bool
write(string $cmd)

Inputs a command into an interactive shell.

from  SSH2
bool
startSubsystem(string $subsystem)

Start a subsystem.

from  SSH2
bool
stopSubsystem()

Stops a subsystem.

from  SSH2
reset()

Closes a channel

from  SSH2
isTimeout()

Is timeout?

from  SSH2
disconnect()

Disconnect

from  SSH2
__destruct()

Destructor.

from  SSH2
bool
isConnected()

Is the connection still active?

from  SSH2
bool
isAuthenticated()

Have you successfully been logged in?

from  SSH2
bool
ping()

Pings a server connection, or tries to reconnect if the connection has gone down

from  SSH2
reset_connection(int $reason)

Resets a connection for re-use

enableQuietMode()

Enable Quiet Mode

from  SSH2
disableQuietMode()

Disable Quiet Mode

from  SSH2
bool
isQuietModeEnabled()

Returns whether Quiet Mode is enabled or not

from  SSH2
enablePTY()

Enable request-pty when using exec()

from  SSH2
disablePTY()

Disable request-pty when using exec()

from  SSH2
bool
isPTYEnabled()

Returns whether request-pty is enabled or not

from  SSH2
mixed
get_channel_packet(int $client_channel, bool $skip_extended = false)

Gets channel data

from  SSH2
bool
send_binary_packet(string $data, string $logged = null)

Sends Binary Packets

from  SSH2
bool
send_channel_packet(int $client_channel, string $data)

Sends channel data

from  SSH2
bool
disconnect_helper(int $reason)

Disconnect

define_array(array ...$args)

Define Array

from  SSH2
array|false|string
getLog()

Returns a log of the packets that have been sent and received.

from  SSH2
string
format_log(array $message_log, array $message_number_log)

Formats a log for printing

from  SSH2
string[]
getErrors()

Returns all errors

from  SSH2
string
getLastError()

Returns the last error

from  SSH2
string
getServerIdentification()

Return the server identification.

from  SSH2
array
getServerAlgorithms()

Returns a list of algorithms the server supports

from  SSH2
static array
getSupportedKEXAlgorithms()

Returns a list of KEX algorithms that phpseclib supports

from  SSH2
static array
getSupportedHostKeyAlgorithms()

Returns a list of host key algorithms that phpseclib supports

from  SSH2
static array
getSupportedEncryptionAlgorithms()

Returns a list of symmetric key algorithms that phpseclib supports

from  SSH2
static array
getSupportedMACAlgorithms()

Returns a list of MAC algorithms that phpseclib supports

from  SSH2
static array
getSupportedCompressionAlgorithms()

Returns a list of compression algorithms that phpseclib supports

from  SSH2
array
getAlgorithmsNegotiated()

Return list of negotiated algorithms

from  SSH2
setTerminal(string $term)

Allows you to set the terminal

from  SSH2
setPreferredAlgorithms(array $methods)

Accepts an associative array with up to four parameters as described at https://www.php.net/manual/en/function.ssh2-connect.php

from  SSH2
string
getBannerMessage()

Returns the banner message.

from  SSH2
mixed
getServerPublicHostKey()

Returns the server public host key.

from  SSH2
false|int
getExitStatus()

Returns the exit status of an SSH command or false.

from  SSH2
int
getWindowColumns()

Returns the number of columns for the terminal window size.

from  SSH2
int
getWindowRows()

Returns the number of rows for the terminal window size.

from  SSH2
setWindowColumns(int $value)

Sets the number of columns for the terminal window size.

from  SSH2
setWindowRows(int $value)

Sets the number of rows for the terminal window size.

from  SSH2
setWindowSize(int $columns = 80, int $rows = 24)

Sets the number of columns and rows for the terminal window size.

from  SSH2
string
__toString()

To String Magic Method

from  SSH2
string
getResourceId()

Get Resource ID

from  SSH2
static bool|SSH2
getConnectionByResourceId(string $id)

Return existing connection

from  SSH2
static SSH2[]
getConnections()

Return all excising connections

from  SSH2
array|null
getAuthMethodsToContinue()

Return the list of authentication methods that may productively continue authentication.

from  SSH2
disableStatCache()

Disable the stat cache

enableStatCache()

Enable the stat cache

clearStatCache()

Clear the stat cache

enablePathCanonicalization()

Enable path canonicalization

disablePathCanonicalization()

Enable path canonicalization

mixed
pwd()

Returns the current directory name

mixed
realpath(string $path)

Canonicalize the Server-Side Path Name

bool
chdir(string $dir)

Changes the current directory

mixed
nlist(string $dir = '.', bool $recursive = false)

Returns a list of files in the given directory

mixed
rawlist(string $dir = '.', bool $recursive = false)

Returns a detailed list of files in the given directory

setListOrder(string[] ...$args)

Defines how nlist() and rawlist() will be sorted - if at all.

mixed
stat(string $filename)

Returns general information about a file.

mixed
lstat(string $filename)

Returns general information about a file or symbolic link.

bool
truncate(string $filename, int $new_size)

Truncates a file to a given length

bool
touch(string $filename, int $time = null, int $atime = null)

Sets access and modification time of file.

bool
chown(string $filename, int $uid, bool $recursive = false)

Changes file or directory owner

bool
chgrp(string $filename, int $gid, bool $recursive = false)

Changes file or directory group

mixed
chmod(int $mode, string $filename, bool $recursive = false)

Set permissions on a file.

mixed
readlink(string $link)

Return the target of a symbolic link

bool
symlink(string $target, string $link)

Create a symlink

bool
mkdir(string $dir, int $mode = -1, bool $recursive = false)

Creates a directory.

bool
rmdir(string $dir)

Removes a directory.

bool
put(string $remote_file, string|resource $data, int $mode = self::SOURCE_STRING, int $start = -1, int $local_start = -1, callable|null $progressCallback = null)

Uploads a file to the SFTP server.

mixed
get(string $remote_file, string|bool|resource|callable $local_file = false, int $offset = 0, int $length = -1, callable|null $progressCallback = null)

Downloads a file from the SFTP server.

bool
delete(string $path, bool $recursive = true)

Deletes a file on the SFTP server.

bool
file_exists(string $path)

Checks whether a file or directory exists

bool
is_dir(string $path)

Tells whether the filename is a directory

bool
is_file(string $path)

Tells whether the filename is a regular file

bool
is_link(string $path)

Tells whether the filename is a symbolic link

bool
is_readable(string $path)

Tells whether a file exists and is readable

bool
is_writable(string $path)

Tells whether the filename is writable

bool
is_writeable(string $path)

Tells whether the filename is writeable

mixed
fileatime(string $path)

Gets last access time of file

mixed
filemtime(string $path)

Gets file modification time

mixed
fileperms(string $path)

Gets file permissions

mixed
fileowner(string $path)

Gets file owner

mixed
filegroup(string $path)

Gets file group

mixed
filesize(string $path)

Gets file size

mixed
filetype(string $path)

Gets file type

bool
rename(string $oldname, string $newname)

Renames a file or a directory on the SFTP server

array
parseAttributes(string $response)

Parse Attributes

array|string
getSFTPLog()

Returns a log of the packets that have been sent and received.

array
getSFTPErrors()

Returns all errors

string
getLastSFTPError()

Returns the last error

array
getSupportedVersions()

Get supported SFTP versions

enableDatePreservation()

Enable Date Preservation

disableDatePreservation()

Disable Date Preservation

Details

SSH2|void __construct(mixed $host, int $port = 22, int $timeout = 10)

Default Constructor.

Connects to an SFTP server

Parameters

mixed $host
int $port
int $timeout

Return Value

SSH2|void

static setCryptoEngine(int $engine)

Set Crypto Engine Mode

Possible $engine values: OpenSSL, mcrypt, Eval, PHP

Parameters

int $engine

sendIdentificationStringFirst()

Send Identification String First

https://tools.ietf.org/html/rfc4253#section-4.2 says "when the connection has been established, both sides MUST send an identification string". It does not say which side sends it first. In theory it shouldn't matter but it is a fact of life that some SSH servers are simply buggy

sendIdentificationStringLast()

Send Identification String Last

https://tools.ietf.org/html/rfc4253#section-4.2 says "when the connection has been established, both sides MUST send an identification string". It does not say which side sends it first. In theory it shouldn't matter but it is a fact of life that some SSH servers are simply buggy

sendKEXINITFirst()

Send SSH_MSG_KEXINIT First

https://tools.ietf.org/html/rfc4253#section-7.1 says "key exchange begins by each sending sending the [SSH_MSG_KEXINIT] packet". It does not say which side sends it first. In theory it shouldn't matter but it is a fact of life that some SSH servers are simply buggy

sendKEXINITLast()

Send SSH_MSG_KEXINIT Last

https://tools.ietf.org/html/rfc4253#section-7.1 says "key exchange begins by each sending sending the [SSH_MSG_KEXINIT] packet". It does not say which side sends it first. In theory it shouldn't matter but it is a fact of life that some SSH servers are simply buggy

bool login(string $username, string|AsymmetricKey|array[]|Agent|null ...$args)

Login

Parameters

string $username
string|AsymmetricKey|array[]|Agent|null ...$args

Return Value

bool

Exceptions

UnexpectedValueException on receipt of unexpected packets

protected bool sublogin(string $username, string[] ...$args)

Login Helper

Parameters

string $username
string[] ...$args

Return Value

bool

See also

\self::_login_helper()

setTimeout(mixed $timeout)

Set Timeout

$ssh->exec('ping 127.0.0.1'); on a Linux host will never return and will run indefinitely. setTimeout() makes it so it'll timeout. Setting $timeout to false or 0 will mean there is no timeout.

Parameters

mixed $timeout

setKeepAlive(int $interval)

Set Keep Alive

Sends an SSH2_MSG_IGNORE message every x seconds, if x is a positive non-zero number.

Parameters

int $interval

getStdError()

Get the output from stdError

string exec(string $command, callable $callback = null)

Execute Command

If $callback is set to false then \phpseclib3\Net\SSH2::get_channel_packet(self::CHANNEL_EXEC) will need to be called manually. In all likelihood, this is not a feature you want to be taking advantage of.

Parameters

string $command
callable $callback

Return Value

string

Exceptions

RuntimeException on connection error

bool requestAgentForwarding()

Request agent forwarding of remote server

Return Value

bool

string|bool|null read(string $expect = '', int $mode = self::READ_SIMPLE)

Returns the output of an interactive shell

Returns when there's a match for $expect, which can take the form of a string literal or, if $mode == self::READ_REGEX, a regular expression.

Parameters

string $expect
int $mode

Return Value

string|bool|null

Exceptions

RuntimeException on connection error

See also

\self::write()

bool write(string $cmd)

Inputs a command into an interactive shell.

Parameters

string $cmd

Return Value

bool

Exceptions

RuntimeException on connection error

See also

\self::read()

bool startSubsystem(string $subsystem)

Start a subsystem.

Right now only one subsystem at a time is supported. To support multiple subsystem's stopSubsystem() could accept a string that contained the name of the subsystem, but at that point, only one subsystem of each type could be opened. To support multiple subsystem's of the same name maybe it'd be best if startSubsystem() generated a new channel id and returns that and then that that was passed into stopSubsystem() but that'll be saved for a future date and implemented if there's sufficient demand for such a feature.

Parameters

string $subsystem

Return Value

bool

See also

\self::stopSubsystem()

bool stopSubsystem()

Stops a subsystem.

Return Value

bool

See also

\self::startSubsystem()

reset()

Closes a channel

If read() timed out you might want to just close the channel and have it auto-restart on the next read() call

isTimeout()

Is timeout?

Did exec() or read() return because they timed out or because they encountered the end?

disconnect()

Disconnect

__destruct()

Destructor.

Will be called, automatically, if you're supporting just PHP5. If you're supporting PHP4, you'll need to call disconnect().

bool isConnected()

Is the connection still active?

Return Value

bool

bool isAuthenticated()

Have you successfully been logged in?

Return Value

bool

bool ping()

Pings a server connection, or tries to reconnect if the connection has gone down

Inspired by http://php.net/manual/en/mysqli.ping.php

Return Value

bool

protected reset_connection(int $reason)

Resets a connection for re-use

Parameters

int $reason

enableQuietMode()

Enable Quiet Mode

Suppress stderr from output

disableQuietMode()

Disable Quiet Mode

Show stderr in output

bool isQuietModeEnabled()

Returns whether Quiet Mode is enabled or not

Return Value

bool

See also

\self::enableQuietMode()
\self::disableQuietMode()

enablePTY()

Enable request-pty when using exec()

disablePTY()

Disable request-pty when using exec()

bool isPTYEnabled()

Returns whether request-pty is enabled or not

Return Value

bool

See also

\self::enablePTY()
\self::disablePTY()

protected mixed get_channel_packet(int $client_channel, bool $skip_extended = false)

Gets channel data

Returns the data as a string. bool(true) is returned if:

  • the server closes the channel
  • if the connection times out
  • if the channel status is CHANNEL_OPEN and the response was CHANNEL_OPEN_CONFIRMATION
  • if the channel status is CHANNEL_REQUEST and the response was CHANNEL_SUCCESS

bool(false) is returned if:

  • if the channel status is CHANNEL_REQUEST and the response was CHANNEL_FAILURE

Parameters

int $client_channel
bool $skip_extended

Return Value

mixed

Exceptions

RuntimeException on connection error

protected bool send_binary_packet(string $data, string $logged = null)

Sends Binary Packets

See '6. Binary Packet Protocol' of rfc4253 for more info.

Parameters

string $data
string $logged

Return Value

bool

See also

\self::_get_binary_packet()

protected bool send_channel_packet(int $client_channel, string $data)

Sends channel data

Spans multiple SSH_MSG_CHANNEL_DATAs if appropriate

Parameters

int $client_channel
string $data

Return Value

bool

protected bool disconnect_helper(int $reason)

Disconnect

Parameters

int $reason

Return Value

bool

protected define_array(array ...$args)

Define Array

Takes any number of arrays whose indices are integers and whose values are strings and defines a bunch of named constants from it, using the value as the name of the constant and the index as the value of the constant. If any of the constants that would be defined already exists, none of the constants will be defined.

Parameters

array ...$args

array|false|string getLog()

Returns a log of the packets that have been sent and received.

Returns a string if NET_SSH2_LOGGING == self::LOG_COMPLEX, an array if NET_SSH2_LOGGING == self::LOG_SIMPLE and false if !defined('NET_SSH2_LOGGING')

Return Value

array|false|string

protected string format_log(array $message_log, array $message_number_log)

Formats a log for printing

Parameters

array $message_log
array $message_number_log

Return Value

string

string[] getErrors()

Returns all errors

Return Value

string[]

string getLastError()

Returns the last error

Return Value

string

string getServerIdentification()

Return the server identification.

Return Value

string

array getServerAlgorithms()

Returns a list of algorithms the server supports

Return Value

array

static array getSupportedKEXAlgorithms()

Returns a list of KEX algorithms that phpseclib supports

Return Value

array

static array getSupportedHostKeyAlgorithms()

Returns a list of host key algorithms that phpseclib supports

Return Value

array

static array getSupportedEncryptionAlgorithms()

Returns a list of symmetric key algorithms that phpseclib supports

Return Value

array

static array getSupportedMACAlgorithms()

Returns a list of MAC algorithms that phpseclib supports

Return Value

array

static array getSupportedCompressionAlgorithms()

Returns a list of compression algorithms that phpseclib supports

Return Value

array

array getAlgorithmsNegotiated()

Return list of negotiated algorithms

Uses the same format as https://www.php.net/ssh2-methods-negotiated

Return Value

array

setTerminal(string $term)

Allows you to set the terminal

Parameters

string $term

setPreferredAlgorithms(array $methods)

Accepts an associative array with up to four parameters as described at https://www.php.net/manual/en/function.ssh2-connect.php

Parameters

array $methods

string getBannerMessage()

Returns the banner message.

Quoting from the RFC, "in some jurisdictions, sending a warning message before authentication may be relevant for getting legal protection."

Return Value

string

mixed getServerPublicHostKey()

Returns the server public host key.

Caching this the first time you connect to a server and checking the result on subsequent connections is recommended. Returns false if the server signature is not signed correctly with the public host key.

Return Value

mixed

Exceptions

RuntimeException on badly formatted keys
NoSupportedAlgorithmsException when the key isn't in a supported format

false|int getExitStatus()

Returns the exit status of an SSH command or false.

Return Value

false|int

int getWindowColumns()

Returns the number of columns for the terminal window size.

Return Value

int

int getWindowRows()

Returns the number of rows for the terminal window size.

Return Value

int

setWindowColumns(int $value)

Sets the number of columns for the terminal window size.

Parameters

int $value

setWindowRows(int $value)

Sets the number of rows for the terminal window size.

Parameters

int $value

setWindowSize(int $columns = 80, int $rows = 24)

Sets the number of columns and rows for the terminal window size.

Parameters

int $columns
int $rows

string __toString()

To String Magic Method

Return Value

string

string getResourceId()

Get Resource ID

We use } because that symbols should not be in URL according to {@link http://tools.ietf.org/html/rfc3986#section-2 RFC}. It will safe us from any conflicts, because otherwise regexp will match all alphanumeric domains.

Return Value

string

static bool|SSH2 getConnectionByResourceId(string $id)

Return existing connection

Parameters

string $id

Return Value

bool|SSH2 will return false if no such connection

static SSH2[] getConnections()

Return all excising connections

Return Value

SSH2[]

array|null getAuthMethodsToContinue()

Return the list of authentication methods that may productively continue authentication.

Return Value

array|null

See also

https://tools.ietf.org/html/rfc4252#section-5.1

disableStatCache()

Disable the stat cache

enableStatCache()

Enable the stat cache

clearStatCache()

Clear the stat cache

enablePathCanonicalization()

Enable path canonicalization

disablePathCanonicalization()

Enable path canonicalization

mixed pwd()

Returns the current directory name

Return Value

mixed

mixed realpath(string $path)

Canonicalize the Server-Side Path Name

SFTP doesn't provide a mechanism by which the current working directory can be changed, so we'll emulate it. Returns the absolute (canonicalized) path.

If canonicalize_paths has been disabled using disablePathCanonicalization(), $path is returned as-is.

Parameters

string $path

Return Value

mixed

Exceptions

UnexpectedValueException on receipt of unexpected packets

See also

\self::chdir()
\self::disablePathCanonicalization()

bool chdir(string $dir)

Changes the current directory

Parameters

string $dir

Return Value

bool

Exceptions

UnexpectedValueException on receipt of unexpected packets

mixed nlist(string $dir = '.', bool $recursive = false)

Returns a list of files in the given directory

Parameters

string $dir
bool $recursive

Return Value

mixed

mixed rawlist(string $dir = '.', bool $recursive = false)

Returns a detailed list of files in the given directory

Parameters

string $dir
bool $recursive

Return Value

mixed

setListOrder(string[] ...$args)

Defines how nlist() and rawlist() will be sorted - if at all.

If sorting is enabled directories and files will be sorted independently with directories appearing before files in the resultant array that is returned.

Any parameter returned by stat is a valid sort parameter for this function. Filename comparisons are case insensitive.

Examples:

$sftp->setListOrder('filename', SORT_ASC); $sftp->setListOrder('size', SORT_DESC, 'filename', SORT_ASC); $sftp->setListOrder(true); Separates directories from files but doesn't do any sorting beyond that $sftp->setListOrder(); Don't do any sort of sorting

Parameters

string[] ...$args

mixed stat(string $filename)

Returns general information about a file.

Returns an array on success and false otherwise.

Parameters

string $filename

Return Value

mixed

mixed lstat(string $filename)

Returns general information about a file or symbolic link.

Returns an array on success and false otherwise.

Parameters

string $filename

Return Value

mixed

bool truncate(string $filename, int $new_size)

Truncates a file to a given length

Parameters

string $filename
int $new_size

Return Value

bool

bool touch(string $filename, int $time = null, int $atime = null)

Sets access and modification time of file.

If the file does not exist, it will be created.

Parameters

string $filename
int $time
int $atime

Return Value

bool

Exceptions

UnexpectedValueException on receipt of unexpected packets

bool chown(string $filename, int $uid, bool $recursive = false)

Changes file or directory owner

Returns true on success or false on error.

Parameters

string $filename
int $uid
bool $recursive

Return Value

bool

bool chgrp(string $filename, int $gid, bool $recursive = false)

Changes file or directory group

Returns true on success or false on error.

Parameters

string $filename
int $gid
bool $recursive

Return Value

bool

mixed chmod(int $mode, string $filename, bool $recursive = false)

Set permissions on a file.

Returns the new file permissions on success or false on error. If $recursive is true than this just returns true or false.

Parameters

int $mode
string $filename
bool $recursive

Return Value

mixed

Exceptions

UnexpectedValueException on receipt of unexpected packets

Return the target of a symbolic link

Parameters

string $link

Return Value

mixed

Exceptions

UnexpectedValueException on receipt of unexpected packets

Create a symlink

symlink() creates a symbolic link to the existing target with the specified name link.

Parameters

string $target
string $link

Return Value

bool

Exceptions

UnexpectedValueException on receipt of unexpected packets

bool mkdir(string $dir, int $mode = -1, bool $recursive = false)

Creates a directory.

Parameters

string $dir
int $mode
bool $recursive

Return Value

bool

bool rmdir(string $dir)

Removes a directory.

Parameters

string $dir

Return Value

bool

Exceptions

UnexpectedValueException on receipt of unexpected packets

bool put(string $remote_file, string|resource $data, int $mode = self::SOURCE_STRING, int $start = -1, int $local_start = -1, callable|null $progressCallback = null)

Uploads a file to the SFTP server.

By default, \phpseclib3\Net\SFTP::put() does not read from the local filesystem. $data is dumped directly into $remote_file. So, for example, if you set $data to 'filename.ext' and then do \phpseclib3\Net\SFTP::get(), you will get a file, twelve bytes long, containing 'filename.ext' as its contents.

Setting $mode to self::SOURCE_LOCAL_FILE will change the above behavior. With self::SOURCE_LOCAL_FILE, $remote_file will contain as many bytes as filename.ext does on your local filesystem. If your filename.ext is 1MB then that is how large $remote_file will be, as well.

Setting $mode to self::SOURCE_CALLBACK will use $data as callback function, which gets only one parameter -- number of bytes to return, and returns a string if there is some data or null if there is no more data

If $data is a resource then it'll be used as a resource instead.

Currently, only binary mode is supported. As such, if the line endings need to be adjusted, you will need to take care of that, yourself.

$mode can take an additional two parameters - self::RESUME and self::RESUME_START. These are bitwise AND'd with $mode. So if you want to resume upload of a 300mb file on the local file system you'd set $mode to the following:

self::SOURCE_LOCAL_FILE | self::RESUME

If you wanted to simply append the full contents of a local file to the full contents of a remote file you'd replace self::RESUME with self::RESUME_START.

If $mode & (self::RESUME | self::RESUME_START) then self::RESUME_START will be assumed.

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

Setting $local_start to > 0 or $mode | self::RESUME_START doesn't do anything unless $mode | self::SOURCE_LOCAL_FILE.

{@internal ASCII mode for SFTPv4/5/6 can be supported by adding a new function - \phpseclib3\Net\SFTP::setMode().}

Parameters

string $remote_file
string|resource $data
int $mode
int $start
int $local_start
callable|null $progressCallback

Return Value

bool

Exceptions

UnexpectedValueException on receipt of unexpected packets
BadFunctionCallException if you're uploading via a callback and the callback function is invalid
FileNotFoundException if you're uploading via a file and the file doesn't exist

mixed get(string $remote_file, string|bool|resource|callable $local_file = false, int $offset = 0, int $length = -1, callable|null $progressCallback = null)

Downloads a file from the SFTP server.

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.

$offset and $length can be used to download files in chunks.

Parameters

string $remote_file
string|bool|resource|callable $local_file
int $offset
int $length
callable|null $progressCallback

Return Value

mixed

Exceptions

UnexpectedValueException on receipt of unexpected packets

bool delete(string $path, bool $recursive = true)

Deletes a file on the SFTP server.

Parameters

string $path
bool $recursive

Return Value

bool

Exceptions

UnexpectedValueException on receipt of unexpected packets

bool file_exists(string $path)

Checks whether a file or directory exists

Parameters

string $path

Return Value

bool

bool is_dir(string $path)

Tells whether the filename is a directory

Parameters

string $path

Return Value

bool

bool is_file(string $path)

Tells whether the filename is a regular file

Parameters

string $path

Return Value

bool

Tells whether the filename is a symbolic link

Parameters

string $path

Return Value

bool

bool is_readable(string $path)

Tells whether a file exists and is readable

Parameters

string $path

Return Value

bool

bool is_writable(string $path)

Tells whether the filename is writable

Parameters

string $path

Return Value

bool

bool is_writeable(string $path)

Tells whether the filename is writeable

Alias of is_writable

Parameters

string $path

Return Value

bool

mixed fileatime(string $path)

Gets last access time of file

Parameters

string $path

Return Value

mixed

mixed filemtime(string $path)

Gets file modification time

Parameters

string $path

Return Value

mixed

mixed fileperms(string $path)

Gets file permissions

Parameters

string $path

Return Value

mixed

mixed fileowner(string $path)

Gets file owner

Parameters

string $path

Return Value

mixed

mixed filegroup(string $path)

Gets file group

Parameters

string $path

Return Value

mixed

mixed filesize(string $path)

Gets file size

Parameters

string $path

Return Value

mixed

mixed filetype(string $path)

Gets file type

Parameters

string $path

Return Value

mixed

bool rename(string $oldname, string $newname)

Renames a file or a directory on the SFTP server

Parameters

string $oldname
string $newname

Return Value

bool

Exceptions

UnexpectedValueException on receipt of unexpected packets

protected array parseAttributes(string $response)

Parse Attributes

See '7. File Attributes' of draft-ietf-secsh-filexfer-13 for more info.

Parameters

string $response

Return Value

array

array|string getSFTPLog()

Returns a log of the packets that have been sent and received.

Returns a string if NET_SFTP_LOGGING == self::LOG_COMPLEX, an array if NET_SFTP_LOGGING == self::LOG_SIMPLE and false if !defined('NET_SFTP_LOGGING')

Return Value

array|string

array getSFTPErrors()

Returns all errors

Return Value

array

string getLastSFTPError()

Returns the last error

Return Value

string

array getSupportedVersions()

Get supported SFTP versions

Return Value

array

enableDatePreservation()

Enable Date Preservation

disableDatePreservation()

Disable Date Preservation