PHP.mk документација

ssh2_sftp

Почист и полокален преглед на PHP референцата, со задржана структура од PHP.net и подобра читливост за примери, секции и белешки.

function.ssh2-sftp.php PHP.net прокси Преводот се освежува
Оригинал на PHP.net
Патека function.ssh2-sftp.php Локална патека за оваа страница.
Извор php.net/manual/en Оригиналниот HTML се реупотребува и локално се стилизира.
Режим Прокси + превод во позадина Кодовите, табелите и белешките остануваат читливи во истиот тек.
ssh2_sftp

Референца за `function.ssh2-sftp.php` со подобрена типографија и навигација.

function.ssh2-sftp.php

ssh2_sftp

(PECL ssh2 >= 0.9.0)

ssh2_sftp(PECL ssh2 >= 0.9.0)

= NULL

ssh2_sftp(resource $session): resource|false

Иницијализирај SFTP подсистем

Параметри

session
Барај SFTP подсистем од веќе поврзан SSH2 сервер. ssh2_connect().

Вратени вредности

SSH конекција идентификатор, добиен од повик до SSH2 SFTP Овој метод враќа ssh2.sftp:// ресурс за употреба со сите други ssh2_sftp_*() методи и false при неуспех.

Примери

fopen wrapper, или

<?php
$connection
= ssh2_connect('shell.example.com', 22);
ssh2_auth_password($connection, 'username', 'password');

$sftp = ssh2_sftp($connection);

$stream = fopen('ssh2.sftp://' . intval($sftp) . '/path/to/file', 'r');
?>

Види Исто така

Белешки од корисници 13 белешки

- Испрати датотека преку SCP
19 години пред
Here is an example of how to send a file with SFTP:

<?php

class SFTPConnection
{
    private $connection;
    private $sftp;

    public function __construct($host, $port=22)
    {
        $this->connection = @ssh2_connect($host, $port);
        if (! $this->connection)
            throw new Exception("Could not connect to $host on port $port.");
    }

    public function login($username, $password)
    {
        if (! @ssh2_auth_password($this->connection, $username, $password))
            throw new Exception("Could not authenticate with username $username " .
                                "and password $password.");

        $this->sftp = @ssh2_sftp($this->connection);
        if (! $this->sftp)
            throw new Exception("Could not initialize SFTP subsystem.");
    }

    public function uploadFile($local_file, $remote_file)
    {
        $sftp = $this->sftp;
        $stream = @fopen("ssh2.sftp://$sftp$remote_file", 'w');

        if (! $stream)
            throw new Exception("Could not open file: $remote_file");

        $data_to_send = @file_get_contents($local_file);
        if ($data_to_send === false)
            throw new Exception("Could not open local file: $local_file.");

        if (@fwrite($stream, $data_to_send) === false)
            throw new Exception("Could not send data from file: $local_file.");

        @fclose($stream);
    }
}

try
{
    $sftp = new SFTPConnection("localhost", 22);
    $sftp->login("username", "password");
    $sftp->uploadFile("/tmp/to_be_sent", "/tmp/to_be_received");
}
catch (Exception $e)
{
    echo $e->getMessage() . "\n";
}

?>
David Barnes
пред 10 години
Note that you must enter the full wrapper URI order for functions that accept those parameters to work properly. For example, this (which is referenced more than once in other comments) does not work:

while (false !== ($file = readdir($handle))) if (is_dir($file)) { /* ... */ }

This does work:

$sc = ssh2_sftp(...);
while (false !== ($file = readdir($handle))) if (is_dir("ssh2.sftp://$sc/$file")) { /* ... */ }

You need to pass the "path" into these functions as an fopen() wrapper URI.
Josh
пред 17 години
I added some functionality for scanning the filesystem and receiving and deleting files.

class SFTPConnection
{
    private $connection;
    private $sftp;

    public function __construct($host, $port=22)
    {
        $this->connection = @ssh2_connect($host, $port);
        if (! $this->connection)
            throw new Exception("Could not connect to $host on port $port.");
    }

    public function login($username, $password)
    {
        if (! @ssh2_auth_password($this->connection, $username, $password))
            throw new Exception("Could not authenticate with username $username " . "and password $password.");
        $this->sftp = @ssh2_sftp($this->connection);
        if (! $this->sftp)
            throw new Exception("Could not initialize SFTP subsystem.");
    }

    public function uploadFile($local_file, $remote_file)
    {
        $sftp = $this->sftp;
        $stream = @fopen("ssh2.sftp://$sftp$remote_file", 'w');
        if (! $stream)
            throw new Exception("Could not open file: $remote_file");
        $data_to_send = @file_get_contents($local_file);
        if ($data_to_send === false)
            throw new Exception("Could not open local file: $local_file.");
        if (@fwrite($stream, $data_to_send) === false)
            throw new Exception("Could not send data from file: $local_file.");
        @fclose($stream);
    }
    
        function scanFilesystem($remote_file) {
              $sftp = $this->sftp;
            $dir = "ssh2.sftp://$sftp$remote_file";  
              $tempArray = array();
            $handle = opendir($dir);
          // List all the files
            while (false !== ($file = readdir($handle))) {
            if (substr("$file", 0, 1) != "."){
              if(is_dir($file)){
//                $tempArray[$file] = $this->scanFilesystem("$dir/$file");
               } else {
                 $tempArray[]=$file;
               }
             }
            }
           closedir($handle);
          return $tempArray;
        }    

    public function receiveFile($remote_file, $local_file)
    {
        $sftp = $this->sftp;
        $stream = @fopen("ssh2.sftp://$sftp$remote_file", 'r');
        if (! $stream)
            throw new Exception("Could not open file: $remote_file");
        $contents = fread($stream, filesize("ssh2.sftp://$sftp$remote_file"));            
        file_put_contents ($local_file, $contents);
        @fclose($stream);
    }
        
    public function deleteFile($remote_file){
      $sftp = $this->sftp;
      unlink("ssh2.sftp://$sftp$remote_file");
    }
}
Josh
пред 17 години
I changed the read function to:

    public function receiveFile($remote_file, $local_file)
    {
        $sftp = $this->sftp;
        $stream = @fopen("ssh2.sftp://$sftp$remote_file", 'r');
        if (! $stream)
            throw new Exception("Could not open file: $remote_file");
        $size = $this->getFileSize($remote_file);            
        $contents = '';
        $read = 0;
        $len = $size;
        while ($read < $len && ($buf = fread($stream, $len - $read))) {
          $read += strlen($buf);
          $contents .= $buf;
        }        
        file_put_contents ($local_file, $contents);
        @fclose($stream);
    }

    public function getFileSize($file){
      $sftp = $this->sftp;
        return filesize("ssh2.sftp://$sftp$file");
    }
bas weerman
пред 18 години
The sftp class provided by David Barnes works great.  However, if you get errors about fopen and it failing to open a stream, try the fully qualified path on the remote server.

For example, if you are uploading a file to /Users/username/Sites/file.txt this may not work:

<?php
try {
    $sftp = new SFTPConnection("localhost", 22);
    $sftp->login("username", "password");
    $sftp->uploadFile("/tmp/to_be_sent", "Sites/file.txt");
}
catch (Exception $e) {
    echo $e->getMessage() . "\n";
}
?>

but this will:

<?php
try {
    $sftp = new SFTPConnection("localhost", 22);
    $sftp->login("username", "password");
    $sftp->uploadFile("/tmp/to_be_sent", "/Users/username/Sites/file.txt");
}
catch (Exception $e) {
    echo $e->getMessage() . "\n";
}
?>

Don't assume that since you are connecting as that user that you are starting in its home space.

Another possible option is that you need to use http://us.php.net/manual/en/function.ssh2-sftp-mkdir.php first to make the directory if it does not exist already, and then upload the file into it.
Curtis Wyatt
пред 11 години
When uploading (writing) a file you must use an absolute path, not a relative one. 

If, like me, you want to use a relative path, you can use the following code: 

$fh=fopen("ssh2.sftp://$sftp".ssh2_sftp_realpath($sftp,".")."/fileinmyhomedir.txt");
Jaybee
пред 16 години
In

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

please make sure that you are specifying the "absolute" path to a file.

If not, you'll get errors like

"Unable to open file ..."

The reasoning is simple ... ssh2.sftp://$sftp points to the "root" directory on the remote server, where, most likely, one does not have access.

It is necessary to point it to your "home" directory.  For example, "ssh2.sftp://$sftp/home/username/filename" ... where "/home/username" is where your home directory is.
sandipshah at vthrive dot com
пред 10 години
If you wish to store once the protocol + ressource used ("ssh2.sftp://$sftp";)
There's a little trick to know... 
This won't work :

<?php
function connect(){
    $connection = ssh2_connect('shell.example.com', 22);
    ssh2_auth_password($connection, 'username', 'password');
    $sftp = ssh2_sftp($connection); 
    return "ssh2.sftp://$sftp";
}
$remote = connect();
is_file( $remote."/path/to/file"); 
// Warning
// Message: is_file(): ## is not a valid SSH2 SFTP resource
?>

You need to have $sftp still avaible at moment the function (is_file, filesize, fopen, ...) uses it
Otherwise, I guess the GC cleans it up and closes the ssh2_stfp connection
That's why this work :

<?php
function connect(){
    //...
    global $sftp;
    $sftp = ssh2_sftp($connection); 
    return "ssh2.sftp://$sftp";
}
$remote = connect();
is_file( $remote."/path/to/file");

// Or way better :

class myClass {
    public function connect(){
        //...
        $this->sftp     = ssh2_sftp($connection); 
        $this->remote   = "ssh2.sftp://".$this->sftp;
    }
    public function test(){
        is_file( $this->remote."/path/to/file");
    }
}
$obj = new myClass();
$obj->connect();
$obj->test();
?>
webakiro at gmail dot com
пред 8 години
David's code works wonderfully except for one thing, it wouldn't upload a file until I placed a forward slash after '$sftp'
    
public function uploadFile($local_file, $remote_file)
    {
        $sftp = $this->sftp;
        // Original
        // "ssh2.sftp://$sftp$remote_file"
        $stream = @fopen("ssh2.sftp://$sftp/$remote_file", 'w');

        if (! $stream)
            throw new Exception("Could not open file: $remote_file");

        $data_to_send = @file_get_contents($local_file);
        if ($data_to_send === false)
            throw new Exception("Could not open local file: $local_file.");

        if (@fwrite($stream, $data_to_send) === false)
            throw new Exception("Could not send data from file: $local_file.");

        @fclose($stream);
    }
Jarrod Christman
пред 6 години
Adding a function to previous class to connect with key instead of user/password

<?php
public function loginWithKey($username, $publicKey, $privateKey, $passphrase = null)
  {
    if (!@ssh2_auth_pubkey_file($this->connection, $username, $publicKey, $privateKey, $passphrase)) {
      throw new Exception("Could not authenticate with given keys or passphrase");
    }

    $this->sftp = @ssh2_sftp($this->connection);
    if (!$this->sftp) {
      throw new Exception("Could not initialize SFTP subsystem.");
    }
  }

?>
Youz
пред 7 години
Remember to use stream_set_chunk_size() on the resource for performance reasons, especially if you're uploading large files on links with high latency.

SFTP can only send 32K of data in one packet and libssh2 will wait for a response after each packet sent. So with a default chunk size of 8K the upload will be very slow.
If you set the chunk size to for example 1Mb, libssh2 will send that chunk in multiple packets of 32K and then wait for a response, making the upload much faster.
(see man libssh2_sftp_write for more details)

<?php
$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", 'w');

stream_set_chunk_size($stream, 1024*1024);
fwrite($stream, $data);
?>
btafoya на briantafoya точка com
пред 9 години
Here is a modified SFTPConnection class previously posted that returns a recursive directory scanFilesystem method.

<?php
class SFTPConnection
{
    private $connection;
    private $sftp;

    public function __construct($host, $port=22)
    {
        $this->connection = @ssh2_connect($host, $port);
        if (! $this->connection)
            throw new Exception("Could not connect to $host on port $port.");
    }

    public function login($username, $password)
    {
        if (! @ssh2_auth_password($this->connection, $username, $password))
            throw new Exception("Could not authenticate with username $username " . "and password $password.");
        $this->sftp = @ssh2_sftp($this->connection);
        if (! $this->sftp)
            throw new Exception("Could not initialize SFTP subsystem.");
    }

    public function uploadFile($local_file, $remote_file)
    {
        $sftp = $this->sftp;
        $stream = @fopen("ssh2.sftp://$sftp$remote_file", 'w');
        if (! $stream)
            throw new Exception("Could not open file: $remote_file");
        $data_to_send = @file_get_contents($local_file);
        if ($data_to_send === false)
            throw new Exception("Could not open local file: $local_file.");
        if (@fwrite($stream, $data_to_send) === false)
            throw new Exception("Could not send data from file: $local_file.");
        @fclose($stream);
    }

    function scanFilesystem($remote_file) {
        $sftp = $this->sftp;
        $dir = "ssh2.sftp://$sftp$remote_file";
        $tempArray = array();

        if (is_dir($dir)) {
            if ($dh = opendir($dir)) {
                while (($file = readdir($dh)) !== false) {
                    $filetype = filetype($dir . $file);
                    if($filetype == "dir") {
                        $tmp = $this->scanFilesystem($remote_file . $file . "/");
                        foreach($tmp as $t) {
                            $tempArray[] = $file . "/" . $t;
                        }
                    } else {
                        $tempArray[] = $file;
                    }
                }
                closedir($dh);
            }
        }

        return $tempArray;
    }

    public function receiveFile($remote_file, $local_file)
    {
        $sftp = $this->sftp;
        $stream = @fopen("ssh2.sftp://$sftp$remote_file", 'r');
        if (! $stream)
            throw new Exception("Could not open file: $remote_file");
        $contents = fread($stream, filesize("ssh2.sftp://$sftp$remote_file"));
        file_put_contents ($local_file, $contents);
        @fclose($stream);
    }

    public function deleteFile($remote_file){
        $sftp = $this->sftp;
        unlink("ssh2.sftp://$sftp$remote_file");
    }
}
?>
duke1 на drakkon точка net
пред 17 години
if anyone is interested on how to get a directory listing:
$SSH_CONNECTION= ssh2_connect('shell.example.com', 22);
ssh2_auth_password($SSH_CONNECTION, 'username', 'password');
//------------------------------------------------------------------- 
//this function finds all files within  given directory and returns them
function scanFilesystem($dir) {
    $tempArray = array();
    $handle = opendir($dir);
  // List all the files
    while (false !== ($file = readdir($handle))) {
    if (substr("$file", 0, 1) != "."){
           if(is_dir($file)){
            $tempArray[$file]=scanFilesystem("$dir/$file");
        } else {
            $tempArray[]=$file;
        }
    }
    }
   closedir($handle); 
  return $tempArray;
}

//------------------------------------------------------------------- 
$sftp = ssh2_sftp($SSH_CONNECTION);

//code to get listing of all OUTGOING files
$dir = "ssh2.sftp://$sftp/outgoing";
$outgoing = scanFilesystem($dir);
sort($outgoing);
print_r($outgoing);
На оваа страница

Автоматски outline од активната документација.

Насловите ќе се појават тука по вчитување.

Попрегледно читање

Примерите, changelog табелите и user notes се визуелно издвоени за да не се губат во долгата содржина.

Брз совет Користи го outline-от Скокни директно на главните секции од активната страница.
Извор Оригиналниот линк останува достапен Кога ти треба целосен upstream context, отвори го PHP.net во нов tab.