How to SFTP with PHP?

indranama picture indranama · Jan 14, 2011 · Viewed 157.1k times · Source

I have came across many PHP scripts for web FTP clients. I need to implement a SFTP client as a web application in PHP. Does PHP support for SFTP? I couldn't find any samples. Can anyone help me with this?

Answer

Gordon picture Gordon · Jan 14, 2011

PHP has ssh2 stream wrappers (disabled by default), so you can use sftp connections with any function that supports stream wrappers by using ssh2.sftp:// for protocol, e.g.

file_get_contents('ssh2.sftp://user:[email protected]:22/path/to/filename');

or - when also using the ssh2 extension

$connection = ssh2_connect('shell.example.com', 22);
ssh2_auth_password($connection, 'username', 'password');
$sftp = ssh2_sftp($connection);
$stream = fopen("ssh2.sftp://$sftp/path/to/file", 'r');

See http://php.net/manual/en/wrappers.ssh2.php

On a side note, there is also quite a bunch of questions about this topic already: