Establish a constant (S)FTP connection with PHP Daemon script

Is there a way to establish a constant connection to a FTP or SFTP server using the built-in PHP functions in a PHP file, which is being run as a Daemon process? At present I use something like:

$connection = ssh2_connect('ip', port);
ssh2_auth_password($connection, 'root', 'password');

$sftp = ssh2_sftp($connection);
$dir = 'ssh2.sftp://' . $sftp . '/./';

But I have to open new connection every time I have to perform an action such as creating, editing or deleting a file or listing a directory.

Thanks in advance.

Upvotes: 1

Views: 204

Answers (1)

Martin Prikryl
Martin Prikryl

Reputation: 202292

You do not have to open new connection for every action.

The $sftp is a resource that represents the connection. Just keep it and reuse it for every action.

$connection = ssh2_connect('ip', port);
ssh2_auth_password($connection, 'root', 'password');

$sftp = ssh2_sftp($connection);

$stream1 = fopen("ssh2.sftp://$sftp/path/to/file", 'r');

// later...

$stream2 = fopen("ssh2.sftp://$sftp/path/to/file", 'r');

Upvotes: 1

Related Questions