SFTP

Extends\phpseclib3\Net\SSH2

Pure-PHP implementations of SFTP.

author

Jim Wigginton terrafrost@php.net

package

Default

Methods

Default Constructor.

__construct(mixed $host,integer $port = 22,integer $timeout = 10)
inherited

$host can either be a string, representing the host, or a stream resource.

see \phpseclib3\Net\SSH2::login()

Arguments

$host

mixed

$port

integer

$timeout

integer

Destructor.

__destruct()
inherited

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

__toString

__toString()
inherited

Logs data packets

append_log(string $message_number,string $message)
inherited

Makes sure that only the last 1MB worth of packets will be logged

Arguments

$message_number

string

$message

string

Logs data packet helper

append_log_helper(integer $constant,string $message_number,string $message,array &$message_number_log,array &$message_log, &$log_size, &$realtime_log_file, &$realtime_log_wrap, &$realtime_log_size)
inherited

Arguments

$constant

integer

$message_number

string

$message

string

$message_number_log

array

$message_log

array

$log_size

$realtime_log_file

$realtime_log_wrap

$realtime_log_size

Returns the first value of the intersection of two arrays or false if the intersection is empty. The order is defined by the first parameter.

array_intersect_first(array $array1,array $array2): mixed
inheritedstatic

Arguments

$array1

array

$array2

array

Response

mixed

False if intersection is empty, else intersected value.

bad_algorithm_candidate

bad_algorithm_candidate( $algorithm)
inheritedstatic

Arguments

$algorithm

Changes the current directory

chdir(string $dir): boolean
Throws
\UnexpectedValueException

on receipt of unexpected packets

Arguments

$dir

string

Response

boolean

Changes file or directory group

chgrp(string $filename,integer|string $gid,boolean $recursive = false): boolean

$gid should be an int for SFTPv3 and a string for SFTPv4+. Ideally the string would be of the form "user@dns_domain" but it does not need to be. $sftp->getSupportedVersions()['version'] will return the specific version that's being used.

Returns true on success or false on error.

Arguments

$filename

string

$gid

integer|string

$recursive

boolean

Response

boolean

Set permissions on a file.

chmod(integer $mode,string $filename,boolean $recursive = false): mixed

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

Throws
\UnexpectedValueException

on receipt of unexpected packets

Arguments

$mode

integer

$filename

string

$recursive

boolean

Response

mixed

Changes file or directory owner

chown(string $filename,integer|string $uid,boolean $recursive = false): boolean

$uid should be an int for SFTPv3 and a string for SFTPv4+. Ideally the string would be of the form "user@dns_domain" but it does not need to be. $sftp->getSupportedVersions()['version'] will return the specific version that's being used.

Returns true on success or false on error.

Arguments

$filename

string

$uid

integer|string

$recursive

boolean

Response

boolean

Clear the stat cache

clearStatCache()

Closes and flushes a channel

close_channel(integer $client_channel,boolean $want_reply = false): void
inherited

\phpseclib3\Net\SSH2 doesn't properly close most channels. For exec() channels are normally closed by the server and for SFTP channels are presumably closed when the client disconnects. This functions is intended for SCP more than anything.

Arguments

$client_channel

integer

$want_reply

boolean

Close handle

close_handle(string $handle): boolean
Throws
\UnexpectedValueException

on receipt of unexpected packets

Arguments

$handle

string

Response

boolean

Compares two rawlist entries using parameters set by setListOrder()

comparator(array $a,array $b): integer

Intended for use with uasort()

Arguments

$a

array

$b

array

Response

integer

Connect to an SSHv2 server

connect()
inherited
Throws
\UnexpectedValueException

on receipt of unexpected packets

\RuntimeException

on other errors

Define Array

define_array(array<mixed,mixed> $args)
inherited

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.

access

protected

Arguments

$args

array<mixed,mixed>

Deletes a file on the SFTP server.

delete(string $path,boolean $recursive = true): boolean
Throws
\UnexpectedValueException

on receipt of unexpected packets

Arguments

$path

string

$recursive

boolean

Response

boolean

Recursively deletes directories on the SFTP server

delete_recursive(string $path,integer &$i): boolean

Minimizes directory lookups and SSH_FXP_STATUS requests for speed.

Arguments

$path

string

$i

integer

Response

boolean

Disable arbitrary length packets

disableArbitraryLengthPackets()

Disable Date Preservation

disableDatePreservation()

Disable path canonicalization

disablePathCanonicalization()

If this is enabled then $sftp->pwd() will not return the canonicalized absolute path

Disable request-pty when using exec()

disablePTY()
inherited

Disable Quiet Mode

disableQuietMode()
inherited

Show stderr in output

Disables "smart" multi-factor authentication (MFA)

disableSmartMFA()
inherited

Disable the stat cache

disableStatCache()

Disconnect

disconnect()
inherited

Disconnect

disconnect_helper(integer $reason): false
inherited

Arguments

$reason

integer

Response

false

Enable arbitrary length packets

enableArbitraryLengthPackets()

Enable Date Preservation

enableDatePreservation()

Enable path canonicalization

enablePathCanonicalization()

Enable request-pty when using exec()

enablePTY()
inherited

Enable Quiet Mode

enableQuietMode()
inherited

Suppress stderr from output

Enables "smart" multi-factor authentication (MFA)

enableSmartMFA()
inherited

Enable the stat cache

enableStatCache()

Maps an encryption algorithm name to an instance of a subclass of \phpseclib3\Crypt\Common\SymmetricKey.

encryption_algorithm_to_crypt_instance(string $algorithm): \phpseclib3\Crypt\Common\SymmetricKey|null
inheritedstatic

Arguments

$algorithm

string

Name of the encryption algorithm

Response

\phpseclib3\Crypt\Common\SymmetricKey|null

Maps an encryption algorithm name to the number of key bytes.

encryption_algorithm_to_key_size(string $algorithm): integer|null
inherited

Arguments

$algorithm

string

Name of the encryption algorithm

Response

integer|null

Number of bytes as an integer or null for unknown

Execute Command

exec(string $command,callable $callback = null): string|boolean
inherited

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.

psalm-return

($callback is callable ? bool : string|bool)

Throws
\RuntimeException

on connection error

Arguments

$command

string

$callback

callable

Response

string|boolean

Checks whether a file or directory exists

file_exists(string $path): boolean

Arguments

$path

string

Response

boolean

Gets last access time of file

fileatime(string $path): mixed

Arguments

$path

string

Response

mixed

Gets file group

filegroup(string $path): mixed

Arguments

$path

string

Response

mixed

Gets file modification time

filemtime(string $path): mixed

Arguments

$path

string

Response

mixed

Gets file owner

fileowner(string $path): mixed

Arguments

$path

string

Response

mixed

Gets file permissions

fileperms(string $path): mixed

Arguments

$path

string

Response

mixed

Gets file size

filesize(string $path): mixed

Arguments

$path

string

Response

mixed

Gets file type

filetype(string $path): string|false

Arguments

$path

string

Response

string|false

Filter Binary Packets

filter(string $payload,boolean $skip_channel_filter): string|boolean
inherited

Because some binary packets need to be ignored...

see self::_get_binary_packet()

Arguments

$payload

string

$skip_channel_filter

boolean

Response

string|boolean

Formats a log for printing

format_log(array $message_log,array $message_number_log): string
inherited

Arguments

$message_log

array

$message_number_log

array

Response

string

Generates the SSH identifier

generate_identifier(): string
inherited

You should overwrite this method in your own class if you want to use another identifier

Response

string

Downloads a file from the SFTP server.

get(string $remote_file,string|boolean|resource|callable $local_file = false,integer $offset,integer $length = -1,callable|null $progressCallback = null): string|boolean

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.

Throws
\UnexpectedValueException

on receipt of unexpected packets

Arguments

$remote_file

string

$local_file

string|boolean|resource|callable

$offset

integer

$length

integer

$progressCallback

callable|null

Response

string|boolean

Gets Binary Packets

get_binary_packet(boolean $skip_channel_filter = false): boolean|string
inherited

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

see self::_send_binary_packet()

Arguments

$skip_channel_filter

boolean

Response

boolean|string

Gets channel data

get_channel_packet(integer $client_channel,boolean $skip_extended = false): mixed
inherited

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
Throws
\RuntimeException

on connection error

Arguments

$client_channel

integer

$skip_extended

boolean

Response

mixed

Return the channel to be used with read() / write()

get_interactive_channel(): integer
inherited

Return an lstat properity

get_lstat_cache_prop(string $path,string $prop): mixed

Uses cache if appropriate.

Arguments

$path

string

$prop

string

Response

mixed

Return an available open channel

get_open_channel(): integer
inherited

Response

integer

Receives SFTP Packets

get_sftp_packet( $request_id = null): string

See '6. General Packet Format' of draft-ietf-secsh-filexfer-13 for more info.

Incidentally, the number of SSH_MSG_CHANNEL_DATA messages has no bearing on the number of SFTP packets present. There can be one SSH_MSG_CHANNEL_DATA messages containing two SFTP packets or there can be two SSH_MSG_CHANNEL_DATA messages containing one SFTP packet.

see self::_send_sftp_packet()

Arguments

$request_id

Response

string

Return a stat properity

get_stat_cache_prop(string $path,string $prop): mixed

Uses cache if appropriate.

Arguments

$path

string

$prop

string

Response

mixed

Return a stat or lstat properity

get_xstat_cache_prop(string $path,string $prop,string $type): mixed

Uses cache if appropriate.

Arguments

$path

string

$prop

string

$type

string

Response

mixed

Return list of negotiated algorithms

getAlgorithmsNegotiated(): array
inherited

Response

array

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

getAuthMethodsToContinue(): array|null
inherited
see https://tools.ietf.org/html/rfc4252#section-5.1

Response

array|null

Returns the banner message.

getBannerMessage(): string
inherited

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

Response

string

Return existing connection

getConnectionByResourceId(string $id): boolean|\phpseclib3\Net\SSH2
inheritedstatic

Arguments

$id

string

Response

boolean|\phpseclib3\Net\SSH2

will return false if no such connection

Return all excising connections

getConnections(): \phpseclib3\Net\array<string,
inheritedstatic

Response

\phpseclib3\Net\array

SSH2>

Returns all errors

getErrors(): array<mixed,string>
inherited

Response

array<mixed,string>

Returns the exit status of an SSH command or false.

getExitStatus(): false|integer
inherited

Response

false|integer

Returns the last error

getLastError(): string
inherited

Response

string

Returns the last error

getLastSFTPError(): string

Response

string

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

getLog(): array|false|string
inherited

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')

Response

array|false|string

Get supported SFTP versions

getNegotiatedVersion(): integer|false

Response

integer|false

Get Resource ID

getResourceId(): string
inherited

We use {} because that symbols should not be in URL according to RFC. It will safe us from any conflicts, because otherwise regexp will match all alphanumeric domains.

Response

string

Returns a list of algorithms the server supports

getServerAlgorithms(): array
inherited

Response

array

Return the server identification.

getServerIdentification(): string|false
inherited

Response

string|false

Returns the server public host key.

getServerPublicHostKey(): string|false
inherited

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.

Throws
\RuntimeException

on badly formatted keys

\phpseclib3\Exception\NoSupportedAlgorithmsException

when the key isn't in a supported format

Response

string|false

Returns all errors

getSFTPErrors(): array

Response

array

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

getSFTPLog(): array|string

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')

Response

array|string

Get the output from stdError

getStdError()
inherited

Returns a list of compression algorithms that phpseclib supports

getSupportedCompressionAlgorithms(): array
inheritedstatic

Response

array

Returns a list of symmetric key algorithms that phpseclib supports

getSupportedEncryptionAlgorithms(): array
inheritedstatic

Response

array

Returns a list of host key algorithms that phpseclib supports

getSupportedHostKeyAlgorithms(): array
inheritedstatic

Response

array

Returns a list of KEX algorithms that phpseclib supports

getSupportedKEXAlgorithms(): array
inheritedstatic

Response

array

Returns a list of MAC algorithms that phpseclib supports

getSupportedMACAlgorithms(): array
inheritedstatic

Response

array

Get supported SFTP versions

getSupportedVersions(): array

Response

array

Returns the number of columns for the terminal window size.

getWindowColumns(): integer
inherited

Response

integer

Returns the number of rows for the terminal window size.

getWindowRows(): integer
inherited

Response

integer

(Re)initializes the SFTP channel

init_sftp_connection(): boolean

Response

boolean

Creates an interactive shell

initShell(): boolean
inherited
see \phpseclib3\Net\SSH2::read()\phpseclib3\Net\SSH2::write()
Throws
\UnexpectedValueException

on receipt of unexpected packets

\RuntimeException

on other errors

Response

boolean

Tells whether the filename is a directory

is_dir(string $path): boolean

Arguments

$path

string

Response

boolean

Tells whether the filename is a regular file

is_file(string $path): boolean

Arguments

$path

string

Response

boolean

Tells whether a file exists and is readable

is_readable(string $path): boolean

Arguments

$path

string

Response

boolean

Tells whether the filename is writable

is_writable(string $path): boolean

Arguments

$path

string

Response

boolean

Tells whether the filename is writeable

is_writeable(string $path): boolean

Alias of is_writable

Arguments

$path

string

Response

boolean

Have you successfully been logged in?

isAuthenticated(): boolean
inherited

Response

boolean

Is the connection still active?

isConnected(): boolean
inherited

Response

boolean

Returns whether request-pty is enabled or not

isPTYEnabled(): boolean
inherited

Returns whether Quiet Mode is enabled or not

isQuietModeEnabled(): boolean
inherited

Is timeout?

isTimeout()
inherited

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

Key Exchange

key_exchange(string|boolean $kexinit_payload_server = false): boolean
inherited
Throws
\UnexpectedValueException

on receipt of unexpected packets

\RuntimeException

on other errors

\phpseclib3\Exception\NoSupportedAlgorithmsException

when none of the algorithms phpseclib has loaded are compatible

Arguments

$kexinit_payload_server

string|boolean

optional

Response

boolean

Handle the keyboard-interactive requests / responses.

keyboard_interactive_process(string|array $responses): boolean
inherited
Throws
\RuntimeException

on connection error

Arguments

$responses

string|array

Response

boolean

Logs errors

logError(string $response,integer $status = -1)

Arguments

$response

string

$status

integer

Returns general information about a file or symbolic link.

lstat(string $filename): array|false

Returns an array on success and false otherwise.

Arguments

$filename

string

Response

array|false

Maps an encryption algorithm name to an instance of a subclass of \phpseclib3\Crypt\Hash.

mac_algorithm_to_hash_instance(string $algorithm): \phpseclib3\Net\array{Hash,
inheritedstatic

Arguments

$algorithm

string

Name of the encryption algorithm

Response

\phpseclib3\Net\array{Hash,

int}|null

Creates a directory.

mkdir(string $dir,integer $mode = -1,boolean $recursive = false): boolean

Arguments

$dir

string

$mode

integer

$recursive

boolean

Response

boolean

Helper function for directory creation

mkdir_helper(string $dir,integer $mode): boolean

Arguments

$dir

string

$mode

integer

Response

boolean

Returns a list of files in the given directory

nlist(string $dir = '.',boolean $recursive = false): array|false

Arguments

$dir

string

$recursive

boolean

Response

array|false

Helper method for nlist

nlist_helper(string $dir,boolean $recursive,string $relativeDir): array|false

Arguments

$dir

string

$recursive

boolean

$relativeDir

string

Response

array|false

Helper function for agent->on_channel_open()

on_channel_open()
inherited

Used when channels are created to inform agent of said channel opening. Must be called after channel open confirmation received

Parse Attributes

parseAttributes(string &$response): array

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

Arguments

$response

string

Response

array

Parse Longname

parseLongname(string $longname): mixed

SFTPv3 doesn't provide any easy way of identifying a file type. You could try to open a file as a directory and see if an error is returned or you could try to parse the SFTPv3-specific longname field of the SSH_FXP_NAME packet. That's what this function does. The result is returned using the SFTPv4 type constants.

If the longname is in an unrecognized format bool(false) is returned.

Arguments

$longname

string

Response

mixed

Attempt to identify the file type

parseMode(integer $mode): integer

Quoting the SFTP RFC, "Implementations MUST NOT send bits that are not defined" but they seem to anyway

Arguments

$mode

integer

Response

integer

Parse Time

parseTime(string $key,integer $flags,string &$response): array

See '7.7. Times' of draft-ietf-secsh-filexfer-13 for more info.

Arguments

$key

string

$flags

integer

$response

string

Response

array

Partially initialize an SFTP connection

partial_init_sftp_connection(): boolean
Throws
\UnexpectedValueException

on receipt of unexpected packets

Response

boolean

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

ping(): boolean
inherited

Response

boolean

Check a few things before SFTP functions are called

precheck(): boolean

Response

boolean

Uploads a file to the SFTP server.

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

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().}

Throws
\UnexpectedValueException

on receipt of unexpected packets

\BadFunctionCallException

if you're uploading via a callback and the callback function is invalid

\phpseclib3\Exception\FileNotFoundException

if you're uploading via a file and the file doesn't exist

Arguments

$remote_file

string

$data

string|resource

$mode

integer

$start

integer

$local_start

integer

$progressCallback

callable|null

Response

boolean

Returns the current directory name

pwd(): string|boolean

Response

string|boolean

Checks cache for path

query_stat_cache(string $path): mixed

Mainly used by file_exists

Arguments

$path

string

Response

mixed

Returns a detailed list of files in the given directory

rawlist(string $dir = '.',boolean $recursive = false): array|false

Arguments

$dir

string

$recursive

boolean

Response

array|false

Returns the output of an interactive shell

read(string $expect = '',integer $mode = self::READ_SIMPLE): string|boolean|null
inherited

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.

see \phpseclib3\Net\SSH2::write()
Throws
\RuntimeException

on connection error

Arguments

$expect

string

$mode

integer

Response

string|boolean|null

Reads multiple successive SSH_FXP_WRITE responses

read_put_responses(integer $i): boolean

Sending an SSH_FXP_WRITE packet and immediately reading its response isn't as efficient as blindly sending out $i SSH_FXP_WRITEs, in succession, and then reading $i responses.

Throws
\UnexpectedValueException

on receipt of unexpected packets

Arguments

$i

integer

Response

boolean

Read Remaining Bytes

read_remaining_bytes(integer $remaining_length): string
inherited
see \phpseclib3\Net\SSH2::get_binary_packet()

Arguments

$remaining_length

integer

Response

string

Reads a list, be it detailed or not, of files in the given directory

readlist(string $dir,boolean $raw = true): array|false
Throws
\UnexpectedValueException

on receipt of unexpected packets

Arguments

$dir

string

$raw

boolean

Response

array|false

Canonicalize the Server-Side Path Name

realpath(string $path): mixed

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.

see \phpseclib3\Net\SFTP::chdir()\phpseclib3\Net\SFTP::disablePathCanonicalization()
Throws
\UnexpectedValueException

on receipt of unexpected packets

Arguments

$path

string

Response

mixed

In situ reconnect method

reconnect(): boolean
inherited

Response

boolean

Remove files / directories from cache

remove_from_stat_cache(string $path): boolean

Arguments

$path

string

Response

boolean

Renames a file or a directory on the SFTP server.

rename(string $oldname,string $newname): boolean

If the file already exists this will return false

Throws
\UnexpectedValueException

on receipt of unexpected packets

Arguments

$oldname

string

$newname

string

Response

boolean

Request agent forwarding of remote server

requestAgentForwarding(): boolean
inherited

Response

boolean

Closes a channel

reset()
inherited

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

Resets a connection for re-use

reset_connection(integer $reason)
inherited

Arguments

$reason

integer

Removes a directory.

rmdir(string $dir): boolean
Throws
\UnexpectedValueException

on receipt of unexpected packets

Arguments

$dir

string

Response

boolean

Sends Binary Packets

send_binary_packet(string $data,string $logged = null): void
inherited

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

see self::_get_binary_packet()

Arguments

$data

string

$logged

string

Sends channel data

send_channel_packet(integer $client_channel,string $data): void
inherited

Spans multiple SSH_MSG_CHANNEL_DATAs if appropriate

Arguments

$client_channel

integer

$data

string

Sends SFTP Packets

send_sftp_packet(integer $type,string $data,integer $request_id = 1): void

See '6. General Packet Format' of draft-ietf-secsh-filexfer-13 for more info.

see self::_get_sftp_packet()self::send_channel_packet()

Arguments

$type

integer

$data

string

$request_id

integer

Send Identification String First

sendIdentificationStringFirst()
inherited

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

Send Identification String Last

sendIdentificationStringLast()
inherited

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

Send SSH_MSG_KEXINIT First

sendKEXINITFirst()
inherited

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

Send SSH_MSG_KEXINIT Last

sendKEXINITLast()
inherited

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

Set Crypto Engine Mode

setCryptoEngine(integer $engine)
inheritedstatic

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

Arguments

$engine

integer

Set Keep Alive

setKeepAlive(integer $interval)
inherited

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

Arguments

$interval

integer

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

setListOrder(string $args)

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

Arguments

$args

string

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

setPreferredAlgorithms(array $methods)
inherited

Arguments

$methods

array

Set preferred version

setPreferredVersion(integer $version)

If you're preferred version isn't supported then the highest supported version of SFTP will be utilized. Set to null or false or int(0) to unset the preferred version

Arguments

$version

integer

Sets information about a file

setstat(string $filename,string $attr,boolean $recursive): boolean
Throws
\UnexpectedValueException

on receipt of unexpected packets

Arguments

$filename

string

$attr

string

$recursive

boolean

Response

boolean

Recursively sets information on directories on the SFTP server

setstat_recursive(string $path,string $attr,integer &$i): boolean

Minimizes directory lookups and SSH_FXP_STATUS requests for speed.

Arguments

$path

string

$attr

string

$i

integer

Response

boolean

Allows you to set the terminal

setTerminal(string $term)
inherited

Arguments

$term

string

Set Timeout

setTimeout(mixed $timeout)
inherited

$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.

Arguments

$timeout

mixed

Sets the number of columns for the terminal window size.

setWindowColumns(integer $value)
inherited

Arguments

$value

integer

Sets the number of rows for the terminal window size.

setWindowRows(integer $value)
inherited

Arguments

$value

integer

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

setWindowSize(integer $columns = 80,integer $rows = 24)
inherited

Arguments

$columns

integer

$rows

integer

Start a subsystem.

startSubsystem(string $subsystem): boolean
inherited

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.

see \phpseclib3\Net\SSH2::stopSubsystem()

Arguments

$subsystem

string

Response

boolean

Returns general information about a file.

stat(string $filename): array|false

Returns an array on success and false otherwise.

Arguments

$filename

string

Response

array|false

Returns general information about a file or symbolic link

stat_helper(string $filename,integer $type): array|false

Determines information without calling \phpseclib3\Net\SFTP::realpath(). The second parameter can be either NET_SFTP_STAT or NET_SFTP_LSTAT.

Throws
\UnexpectedValueException

on receipt of unexpected packets

Arguments

$filename

string

$type

integer

Response

array|false

Stops a subsystem.

stopSubsystem(): boolean
inherited

Login Helper

sublogin(string $username,string $args): boolean
inherited
see self::_login_helper()

Arguments

$username

string

$args

string

Response

boolean

Sets access and modification time of file.

touch(string $filename,integer $time = null,integer $atime = null): boolean

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

Throws
\UnexpectedValueException

on receipt of unexpected packets

Arguments

$filename

string

$time

integer

$atime

integer

Response

boolean

Truncates a file to a given length

truncate(string $filename,integer $new_size): boolean

Arguments

$filename

string

$new_size

integer

Response

boolean

Save files / directories to cache

update_stat_cache(string $path,mixed $value)

Arguments

$path

string

$value

mixed

updateLogHistory

updateLogHistory( $old, $new)
inherited

Arguments

$old

$new

Inputs a command into an interactive shell.

write(string $cmd): void
inherited
see \phpseclib3\Net\SSH2::read()
Throws
\RuntimeException

on connection error

Arguments

$cmd

string

Constants

SFTP channel constant

CHANNEL

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

see

Reads data from a local file.

SOURCE_LOCAL_FILE
see

SOURCE_STRING

SOURCE_STRING

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

SOURCE_CALLBACK
see

Resumes an upload

RESUME
see

Append a local file to an already existing remote file

RESUME_START
see

No compression

NET_SSH2_COMPRESSION_NONE
inherited

zlib compression

NET_SSH2_COMPRESSION_ZLIB
inherited

zlib@openssh.com

NET_SSH2_COMPRESSION_ZLIB_AT_OPENSSH
inherited

MASK_CONSTRUCTOR

MASK_CONSTRUCTOR
inherited

MASK_CONNECTED

MASK_CONNECTED
inherited

MASK_SHELL

MASK_SHELL
inherited

MASK_WINDOW_ADJUST

MASK_WINDOW_ADJUST
inherited

CHANNEL_EXEC

CHANNEL_EXEC
inherited

CHANNEL_SHELL

CHANNEL_SHELL
inherited

CHANNEL_SUBSYSTEM

CHANNEL_SUBSYSTEM
inherited

CHANNEL_AGENT_FORWARD

CHANNEL_AGENT_FORWARD
inherited

CHANNEL_KEEP_ALIVE

CHANNEL_KEEP_ALIVE
inherited

Returns the message numbers

LOG_SIMPLE
inherited
see

Returns the message content

LOG_COMPLEX
inherited
see

Outputs the content real-time

LOG_REALTIME
inherited

Dumps the content real-time to a file

LOG_REALTIME_FILE
inherited

Outputs the message numbers real-time

LOG_SIMPLE_REALTIME
inherited

Make sure that the log never gets larger than this

LOG_MAX_SIZE
inherited
see

Returns when a string matching $expect exactly is found

READ_SIMPLE
inherited
see

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

READ_REGEX
inherited
see

Returns whenever a data packet is received.

READ_NEXT
inherited

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

see

Properties

Packet Types

packet_types :array
see
var
access

private

Type(s)

array

Status Codes

status_codes :array
see
var
access

private

Type(s)

array

string>

attributes :\phpseclib3\Net\array<int,
var

string>

Type(s)

\phpseclib3\Net\array

string>

open_flags :\phpseclib3\Net\array<int,
var

string>

Type(s)

\phpseclib3\Net\array

string>

open_flags5 :\phpseclib3\Net\array<int,
var

string>

Type(s)

\phpseclib3\Net\array

string>

file_types :\phpseclib3\Net\array<int,
var

string>

Type(s)

\phpseclib3\Net\array

The Request ID

use_request_id :boolean

The request ID exists in the off chance that a packet is sent out-of-order. Of course, this library doesn't support concurrent actions, so it's somewhat academic, here.

var
see

Type(s)

boolean

The Packet Type

packet_type :integer

The request ID exists in the off chance that a packet is sent out-of-order. Of course, this library doesn't support concurrent actions, so it's somewhat academic, here.

var
see

Type(s)

integer

Packet Buffer

packet_buffer :string
var
see

Type(s)

string

Extensions supported by the server

extensions :array
var
see

Type(s)

array

Server SFTP version

version :integer
var
see

Type(s)

integer

Default Server SFTP version

defaultVersion :integer
var
see

Type(s)

integer

Preferred SFTP version

preferredVersion :integer
var
see

Type(s)

integer

Current working directory

pwd :string|boolean
var
see

Type(s)

string|boolean

Packet Type Log

packet_type_log :array
see
var

Type(s)

array

Packet Log

packet_log :array
see
var

Type(s)

array

Real-time log file pointer

realtime_log_file :resource|\phpseclib3\Net\closed-resource
inherited
see
var

Type(s)

resource|\phpseclib3\Net\closed-resource

Real-time log file size

realtime_log_size :integer
inherited
see
var

Type(s)

integer

Real-time log file wrap boolean

realtime_log_wrap :boolean
inherited
see
var

Type(s)

boolean

Current log size

log_size :integer
inherited

Should never exceed self::LOG_MAX_SIZE

see
var

Type(s)

integer

Error information

sftp_errors :array
see
var

Type(s)

array

Stat Cache

stat_cache :array

Rather than always having to open a directory and close it immediately there after to see if a file is a directory we'll cache the results.

see
var

Type(s)

array

Max SFTP Packet Size

max_sftp_packet :integer
see
var

Type(s)

integer

Stat Cache Flag

use_stat_cache :boolean
see
var

Type(s)

boolean

Sort Options

sortOptions :array
see
var

Type(s)

array

Canonicalization Flag

canonicalize_paths :boolean

Determines whether or not paths should be canonicalized before being passed on to the remote server.

see
var

Type(s)

boolean

Request Buffers

requestBuffer :array
see
var

Type(s)

array

Preserve timestamps on file downloads / uploads

preserveTime :boolean
see
var

Type(s)

boolean

Arbitrary Length Packets Flag

allow_arbitrary_length_packets :boolean

Determines whether or not packets of any length should be allowed, in cases where the server chooses the packet length (such as directory listings). By default, packets are only allowed to be 256 * 1024 bytes (SFTP_MAX_MSG_LENGTH from OpenSSH's sftp-common.h)

see
var

Type(s)

boolean

Was the last packet due to the channels being closed or not?

channel_close :boolean
see
var

Type(s)

boolean

Has the SFTP channel been partially negotiated?

partial_init :boolean
var

Type(s)

boolean

The SSH identifier

identifier :string
inherited
var

Type(s)

string

The Socket Object

fsock :resource|\phpseclib3\Net\closed-resource|null
inherited
var

Type(s)

resource|\phpseclib3\Net\closed-resource|null

Execution Bitmap

bitmap :integer
inherited

The bits that are set represent functions that have been called already. This is used to determine if a requisite function has been successfully executed. If not, an error should be thrown.

var

Type(s)

integer

Error information

errors :array
inherited
see
var

Type(s)

array

Server Identifier

server_identifier :string|false
inherited
see
var

Type(s)

string|false

Key Exchange Algorithms

kex_algorithms :array|false
inherited
see
var

Type(s)

array|false

Key Exchange Algorithm

kex_algorithm :string|false
inherited
see
var

Type(s)

string|false

Minimum Diffie-Hellman Group Bit Size in RFC 4419 Key Exchange Methods

kex_dh_group_size_min :integer
inherited
see
var

Type(s)

integer

Preferred Diffie-Hellman Group Bit Size in RFC 4419 Key Exchange Methods

kex_dh_group_size_preferred :integer
inherited
see
var

Type(s)

integer

Maximum Diffie-Hellman Group Bit Size in RFC 4419 Key Exchange Methods

kex_dh_group_size_max :integer
inherited
see
var

Type(s)

integer

Server Host Key Algorithms

server_host_key_algorithms :array|false
inherited
see
var

Type(s)

array|false

Encryption Algorithms: Client to Server

encryption_algorithms_client_to_server :array|false
inherited
see
var

Type(s)

array|false

Encryption Algorithms: Server to Client

encryption_algorithms_server_to_client :array|false
inherited
see
var

Type(s)

array|false

MAC Algorithms: Client to Server

mac_algorithms_client_to_server :array|false
inherited
see
var

Type(s)

array|false

MAC Algorithms: Server to Client

mac_algorithms_server_to_client :array|false
inherited
see
var

Type(s)

array|false

Compression Algorithms: Client to Server

compression_algorithms_client_to_server :array|false
inherited
see
var

Type(s)

array|false

Compression Algorithms: Server to Client

compression_algorithms_server_to_client :array|false
inherited
see
var

Type(s)

array|false

Languages: Server to Client

languages_server_to_client :array|false
inherited
see
var

Type(s)

array|false

Languages: Client to Server

languages_client_to_server :array|false
inherited
see
var

Type(s)

array|false

Preferred Algorithms

preferred :array
inherited
see
var

Type(s)

array

Block Size for Server to Client Encryption

encrypt_block_size :integer
inherited

"Note that the length of the concatenation of 'packet_length', 'padding_length', 'payload', and 'random padding' MUST be a multiple of the cipher block size or 8, whichever is larger. This constraint MUST be enforced, even when using stream ciphers."

-- http://tools.ietf.org/html/rfc4253#section-6

see
var

Type(s)

integer

Block Size for Client to Server Encryption

decrypt_block_size :integer
inherited
see
var

Type(s)

integer

Server to Client Encryption Object

decrypt :\phpseclib3\Crypt\Common\SymmetricKey|false
inherited

Decryption Algorithm Name

decryptName :string|null
inherited
var

Type(s)

string|null

Decryption Invocation Counter

decryptInvocationCounter :string|null
inherited

Used by GCM

var

Type(s)

string|null

Fixed Part of Nonce

decryptFixedPart :string|null
inherited

Used by GCM

var

Type(s)

string|null

Server to Client Length Encryption Object

lengthDecrypt :object
inherited
see
var

Type(s)

object

Client to Server Encryption Object

encrypt :\phpseclib3\Crypt\Common\SymmetricKey|false
inherited

Encryption Algorithm Name

encryptName :string|null
inherited
var

Type(s)

string|null

Encryption Invocation Counter

encryptInvocationCounter :string|null
inherited

Used by GCM

var

Type(s)

string|null

Fixed Part of Nonce

encryptFixedPart :string|null
inherited

Used by GCM

var

Type(s)

string|null

Client to Server Length Encryption Object

lengthEncrypt :object
inherited
see
var

Type(s)

object

Client to Server HMAC Object

hmac_create :object
inherited
see
var

Type(s)

object

Client to Server HMAC Name

hmac_create_name :string|false
inherited
var

Type(s)

string|false

Client to Server ETM

hmac_create_etm :integer|false
inherited
var

Type(s)

integer|false

Server to Client HMAC Object

hmac_check :object
inherited
see
var

Type(s)

object

Server to Client HMAC Name

hmac_check_name :string|false
inherited
var

Type(s)

string|false

Server to Client ETM

hmac_check_etm :integer|false
inherited
var

Type(s)

integer|false

Size of server to client HMAC

hmac_size :integer
inherited

We need to know how big the HMAC will be for the server to client direction so that we know how many bytes to read. For the client to server side, the HMAC object will make the HMAC as long as it needs to be. All we need to do is append it.

see
var

Type(s)

integer

Server Public Host Key

server_public_host_key :string
inherited
see
var

Type(s)

string

Session identifier

session_id :string
inherited

"The exchange hash H from the first key exchange is additionally used as the session identifier, which is a unique identifier for this connection."

-- http://tools.ietf.org/html/rfc4253#section-7.2

see
var

Type(s)

string

Exchange hash

exchange_hash :string
inherited

The current exchange hash

see
var

Type(s)

string

Message Numbers

message_numbers :array
inherited
see
var
access

private

Type(s)

array

Disconnection Message 'reason codes' defined in RFC4253

disconnect_reasons :array
inherited
see
var
access

private

Type(s)

array

SSH_MSG_CHANNEL_OPEN_FAILURE 'reason codes', defined in RFC4254

channel_open_failure_reasons :array
inherited
see
var
access

private

Type(s)

array

Terminal Modes

terminal_modes :array
inherited
link

http://tools.ietf.org/html/rfc4254#section-8

see
var
access

private

Type(s)

array

SSH_MSG_CHANNEL_EXTENDED_DATA's data_type_codes

channel_extended_data_type_codes :array
inherited
link

http://tools.ietf.org/html/rfc4254#section-5.2

see
var
access

private

Type(s)

array

Send Sequence Number

send_seq_no :integer
inherited

See 'Section 6.4. Data Integrity' of rfc4253 for more info.

see
var

Type(s)

integer

Get Sequence Number

get_seq_no :integer
inherited

See 'Section 6.4. Data Integrity' of rfc4253 for more info.

see
var

Type(s)

integer

Server Channels

server_channels :array
inherited

Maps client channels to server channels

see
var

Type(s)

array

Channel Buffers

channel_buffers :array
inherited

If a client requests a packet from one channel but receives two packets from another those packets should be placed in a buffer

see
var

Type(s)

array

Channel Status

channel_status :array
inherited

Contains the type of the last sent message

see
var

Type(s)

array

Packet Size

packet_size_client_to_server :array
inherited

Maximum packet size indexed by channel

see
var

Type(s)

array

Message Number Log

message_number_log :array
inherited
see
var

Type(s)

array

Message Log

message_log :array
inherited
see
var

Type(s)

array

The Window Size

window_size :integer
inherited

Bytes the other party can send before it must wait for the window to be adjusted (0x7FFFFFFF = 2GB)

var
see

Type(s)

integer

What we resize the window to

window_resize :integer
inherited

When PuTTY resizes the window it doesn't add an additional 0x7FFFFFFF bytes - it adds 0x40000000 bytes. Some SFTP clients (GoAnywhere) don't support adding 0x7FFFFFFF to the window size after the fact so we'll just do what PuTTY does

var
see

Type(s)

integer

Window size, server to client

window_size_server_to_client :array
inherited

Window size indexed by channel

see
var

Type(s)

array

Window size, client to server

window_size_client_to_server :array
inherited

Window size indexed by channel

see
var

Type(s)

array

Server signature

signature :string
inherited

Verified against $this->session_id

see
var

Type(s)

string

Server signature format

signature_format :string
inherited

ssh-rsa or ssh-dss.

see
var

Type(s)

string

Interactive Buffer

interactiveBuffer :string
inherited
see
var

Type(s)

string

Timeout

timeout :
inherited
see

Type(s)

Current Timeout

curTimeout :
inherited
see

Type(s)

Keep Alive Interval

keepAlive :
inherited
see

Type(s)

Has the signature been validated?

signature_validated :boolean
inherited
see
var

Type(s)

boolean

Flag to suppress stderr from output

quiet_mode :
inherited
see

Type(s)

Time of first network activity

last_packet :float
inherited
var

Type(s)

float

Exit status returned from ssh if any

exit_status :integer
inherited
var

Type(s)

integer

Flag to request a PTY when using exec()

request_pty :boolean
inherited
var
see

Type(s)

boolean

Flag set while exec() is running when using enablePTY()

in_request_pty_exec :boolean
inherited
var

Type(s)

boolean

Flag set after startSubsystem() is called

in_subsystem :boolean
inherited
var

Type(s)

boolean

Contents of stdError

stdErrorLog :string
inherited
var

Type(s)

string

The Last Interactive Response

last_interactive_response :string
inherited
see
var

Type(s)

string

Keyboard Interactive Request / Responses

keyboard_requests_responses :array
inherited
see
var

Type(s)

array

Banner Message

banner_message :string
inherited

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

see
var

Type(s)

string

Did read() timeout or return normally?

is_timeout :boolean
inherited
see
var

Type(s)

boolean

Log Boundary

log_boundary :string
inherited
see
var

Type(s)

string

Log Long Width

log_long_width :integer
inherited
see
var

Type(s)

integer

Log Short Width

log_short_width :integer
inherited
see
var

Type(s)

integer

Hostname

host :string
inherited
see
var

Type(s)

string

Port Number

port :integer
inherited
see
var

Type(s)

integer

Number of columns for terminal window size

windowColumns :integer
inherited
see
var

Type(s)

integer

Number of columns for terminal window size

windowRows :integer
inherited
see
var

Type(s)

integer

Crypto Engine

crypto_engine :integer
inheritedstatic
see
var

Type(s)

integer

A System_SSH_Agent for use in the SSH2 Agent Forwarding scenario

agent :\phpseclib3\System\SSH\Agent
inherited

Connection storage to replicates ssh2 extension functionality: {@link http://php.net/manual/en/wrappers.ssh2.php#refsect1-wrappers.ssh2-examples}

connections :\phpseclib3\Net\array<string,
inheritedstatic
var

SSH2|\WeakReference>

Type(s)

\phpseclib3\Net\array

Send the identification string first?

send_id_string_first :boolean
inherited
var

Type(s)

boolean

Send the key exchange initiation packet first?

send_kex_first :boolean
inherited
var

Type(s)

boolean

Some versions of OpenSSH incorrectly calculate the key size

bad_key_size_fix :boolean
inherited
var

Type(s)

boolean

Should we try to re-connect to re-establish keys?

retry_connect :boolean
inherited
var

Type(s)

boolean

Binary Packet Buffer

binary_packet_buffer :string|false
inherited
var

Type(s)

string|false

Preferred Signature Format

preferred_signature_format :string|false
inherited
var

Type(s)

string|false

Authentication Credentials

auth :array
inherited
var

Type(s)

array

Terminal

term :string
inherited
var

Type(s)

string

The authentication methods that may productively continue authentication.

auth_methods_to_continue :array|null
inherited
see
var

Type(s)

array|null

Compression method

compress :integer
inherited
var

Type(s)

integer

Decompression method

decompress :integer
inherited
var

Type(s)

integer

Compression context

compress_context :resource|false|null
inherited
var

Type(s)

resource|false|null

Decompression context

decompress_context :resource|object
inherited
var

Type(s)

resource|object

Regenerate Compression Context

regenerate_compression_context :boolean
inherited
var

Type(s)

boolean

Regenerate Decompression Context

regenerate_decompression_context :boolean
inherited
var

Type(s)

boolean

Smart multi-factor authentication flag

smartMFA :boolean
inherited
var

Type(s)

boolean