How to SFTP with PHP?

2019-01-01 07:29发布

问题:

I\'ve 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 fot SFTP? I couldn\'t find samples. Can anyone help me with this?

回答1:

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:pass@example.com: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:

  • https://stackoverflow.com/search?q=sftp+php


回答2:

The ssh2 functions aren\'t very good. Hard to use and harder yet to install, using them will guarantee that your code has zero portability. My recommendation would be to use phpseclib, a pure PHP SFTP implementation.



回答3:

I found that \"phpseclib\" should help you with this (SFTP and many more features). http://phpseclib.sourceforge.net/

To Put the file to the server, simply call (Code example from http://phpseclib.sourceforge.net/sftp/examples.html#put)

<?php
include(\'Net/SFTP.php\');

$sftp = new Net_SFTP(\'www.domain.tld\');
if (!$sftp->login(\'username\', \'password\')) {
    exit(\'Login Failed\');
}

// puts a three-byte file named filename.remote on the SFTP server
$sftp->put(\'filename.remote\', \'xxx\');
// puts an x-byte file named filename.remote on the SFTP server,
// where x is the size of filename.local
$sftp->put(\'filename.remote\', \'filename.local\', NET_SFTP_LOCAL_FILE);


回答4:

I performed a full-on cop-out and wrote a class which creates a batch file and then calls sftp via a system call. Not the nicest (or fastest) way of doing it but it works for what I need and it didn\'t require any installation of extra libraries or extensions in PHP.

Could be the way to go if you don\'t want to use the ssh2 extensions



标签: php sftp