Skip to main content

Setting Up SFTP From PHP

PHP's ftp_ssl_connect() function is for SSL-FTP, where as what I need for a client's application is SFTP. Isn't life grand! Well, it's not really too much trouble... PHP can handle that too with functions from the ssh2 PECL extension. I'm just glad I caught it early on instead of at the 11th hour. I figured though I might as well continue my previous post about setting up this project with a brief description on installing ssh2 and testing it to ensure everything is in working order.


The ssh2 extension provides bindings to libssh2 which must be installed first on the system. My target platform is CentOS 5.3, so I was able to install libssh2 and libssh2-devel via yum (using the RPMForge repository).
yum install libssh2 libssh2-devel
The ssh2 extension is available from the website. There is a minor bug in the current version (0.11.0) which prevents it from compiling against PHP 5.3 so I needed to apply this patch.
tar zxf ssh2-0.11.0.tgz
cd ssh2-0.11.0
patch < ../ssh2-php53.patch
I compiled and installed the extension after the code was patched.
./configure --with-ssh2
cp modules/ /usr/local/php/lib/php/extensions/
Adding to php.ini and restarting Apache completed the installation. I was then ready to move on and test it to make sure it worked as it should.

Testing the Extension

Using the extension to upload and retrieve files programmatically over an SFTP connection is relatively simple. First, a secure shell connection is established with the SFTP server using ssh2_connect(), and then a login is authenticated with ssh2_auth_password(). Both functions return false if they fail:
$sess = @ssh2_connect(SFTP_SERVER, SFTP_PORT);
if ($sess === false) {
echo "Connection failed.";
$result = @ssh2_auth_password($sess, SFTP_USERNAME,
if ($result === false) {
echo "Unable to authenticate.";
Once a session has been established, the ssh2_sftp() function is used to retrieve an SFTP resource.
$sftp = @ssh2_sftp($sess);
if ($sftp === false) {
echo "Unable to initialize SFTP subsystem.";
From that point on, the SFTP resource is used with the ssh2.sftp filestream to read and write files.
file_put_contents("ssh2.sftp://" . $sftp . "/tmp/test.txt",
In writing my short automated test case, I dumped some bytes from /dev/urandom to generate a test file, wrote the data to the SFTP server, read it back, and compared the results to make sure they matched after the round-trip.
// generate random data for test file
$data = file_get_contents("/dev/urandom", FILE_BINARY, null,
0, 512);
$data = substr(convert_uuencode($data), 0, 512);

// write data to file on SFTP server
file_put_contents("ssh2.sftp://" . $sftp . "/tmp/test.txt",

// retrieve file from SFTP server
$retrieved = file_get_contents("ssh2.sftp://" . $sftp .

// compare original data with retrieve data
echo ($data == $retrieved) ? "Success!" : "Corruption!";


  1. Very cool Tim! Nice, thorough explanation. Is there a function to read the contents of the directory on the remote server?

  2. Sure you can list the directory contents. You can use any file functions that work with wrappers.

    $files = scandir("ssh2.sftp://" . $sftp . "/home/tboronczyk");

  3. The PECL ssh2 extension is crap. If you want SFTP support, try phpseclib:

  4. Perhaps, Anonymous... but generally a user-land implemented solution is going to execute slower than an extension where the bulk of its code is compiled C. Plus, the ssh2 extension gives a handle that can be used with wrappers, giving a more consistent API. I think I'll stick with the ssh2 extension for now, but thanks for the heads up!

  5. I agree with anonymous. PECL's solution may be faster but that extra speed isn't going to amount to much if you can't even install it.

    And as for stream wrappers... you do realize you can write your own?:

    Personally, I think stream wrappers are overrated. Sure, you get a more consistent API, but you also get a more limited one. And, honestly, I don't think it's even as consistent as you're alleging. Check out the first (and only) example on this page:

    They call ssh2_connect() and ssh2_auth_pubkey_file() and then pass the active handle to the stream. And yet that's consistent? Show me another stream wrapper that does that.

  6. Who said I couldn't install the Pecl extension? ssh2 installed just fine.

  7. I meant "you" in the generic sense. If someone (not necessarily you) can't install the Pecl extension then the speed boost one might gain from using it becomes moot.

  8. Hi,

    I am not get working ssh2_scp_recv function. Here is my program:

    I am getting "Unable to get remote file" error. I have tried with "s" and "" as $RemoteServer value, but no luck.

    For your information I am sure, I have enough read permissions at remote server and write permissions in local server.

    Can't we copy a remote file into our server without $sftp = @ssh2_sftp($sess) like function?

    Please let me know error in my code and how to fix it? Thanks in advance..

    N Naresh Kumar

  9. It looks like you're forgetting the ssh. before sftp. The destination needs to be ssh2.s

  10. newbie sorry:
    what You mean when You write:
    patch < ../ssh2-php53.patch ?
    what You mean when You write:
    phpize ??
    ./configure --with-ssh2

    can You explaine better ?

  11. Im a newbie.
    How am I going to set up this in xampp.


Post a Comment

Popular posts from this blog

Composing Music with PHP

I’m not an expert on probability theory, artificial intelligence, and machine learning. And even my Music 201 class from years ago has been long forgotten. But if you’ll indulge me for the next 10 minutes, I think you’ll find that even just a little knowledge can yield impressive results if creatively woven together. I’d like to share with you how to teach PHP to compose music. Here’s an example: You’re looking at a melody generated by PHP. It’s not the most memorable, but it’s not unpleasant either. And surprisingly, the code to generate such sequences is rather brief. So what’s going on? The script calculates a probability map of melodic intervals and applies a Markov process to generate a new sequence. In friendlier terms, musical data is analyzed by a script to learn which intervals make up pleasing melodies. It then creates a new composition by selecting pitches based on the possibilities it’s observed. . Standing on ShouldersComposition doesn’t happen in a vacuum. Bach was f…

Creepy JavaScript Tracking

I recently began allergy shots so my new Monday morning routine includes me sitting in a doctor's office for 30 minutes (I must wait after receiving the shots and be checked by a nurse to make sure there was no reaction). With nothing else better to do while I waited last week, I started playing around with some JavaScript. This is what I came up with:
<html> <head> <title>Test</title> <script type="text/javascript"> window.onload = function () { var mX = 0,  mY = 0, sX = 0,  sY = 0, queue = [], interval = 200, recIntv = null, playIntv = null, b = document.body, de = document.documentElement, cursor = document.getElementById("cursor"), record = document.getElementById("record"), play = document.getElementById("play"); window.onmousemove = function (e) { e = e || window.event; if (e.pageX || e.pageY) { …

Geolocation Search

Services that allow users to identify nearby points of interest continue to grow in popularity. I'm sure we're all familiar with social websites that let you search for the profiles of people near a postal code, or mobile applications that use geolocation to identify Thai restaurants within walking distance. It's surprisingly simple to implement such functionality, and in this post I will discuss how to do so.

The first step is to obtain the latitude and longitude coordinates of any locations you want to make searchable. In the restaurant scenario, you'd want the latitude and longitude of each eatery. In the social website scenario, you'd want to obtain a list of postal codes with their centroid latitude and longitude.

In general, postal code-based geolocation is a bad idea; their boundaries rarely form simple polygons, the area they cover vary in size, and are subject to change based on the whims of the postal service. But many times we find ourselves stuck on a c…