Php копирование файлов по ssh
In today’s world with so many third-party integrations and content-sharing, it’s important to understand and make use of protocols like SCP and SFTP. PHP’s SSH2 extension, a wrapper for libssh2 which implements the SSH2 protocol, provides several functions you can use to securely transfer files.
Using Wrapper Functions
When a specific file management function doesn’t exist for SFTP or SCP, generally the core file system function will work using a stream wrapper. Below are a few examples:
Before performing any of these calls, the connection to the SSH and SFTP server must be made as it uses the previously created $sftp variable.
User Contributed Notes 13 notes
Here is an example of how to send a file with SFTP:
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 ." );
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" ;
>
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)) < /* . */ >
$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.
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:
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:
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.
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);
>
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");
>
>
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");
>
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:
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.
If you wish to store once the protocol + ressource used ("ssh2.sftp://$sftp";)
There's a little trick to know.
This won't work :
function connect () //.
global $sftp ;
$sftp = ssh2_sftp ( $connection );
return "ssh2.sftp:// $sftp " ;
>
$remote = connect ();
is_file ( $remote . "/path/to/file" );
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 ();
?>
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)
$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 );
?>
Adding a function to previous class to connect with key instead of user/password
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." );
>
>
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.");
Here is a modified SFTPConnection class previously posted that returns a recursive directory scanFilesystem method.
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 );
>
>
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 " );
>
>
?>
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;
>
Установление соединения
Давайте начнем с подключения к службе SSH. Установление соединения выглядит просто:
Некоторые администраторы предпочитают использовать открытые и закрытые ключи для аутентификации входа в систему. Если вы хотите подключиться таким образом, нужно использовать следующий код:
Если при аутентификации вы используете имя пользователя или пароль, открытый или закрытый ключ, функции ssh2_auth_password () и ssh2_auth_pubkey_file () возвращают логическое значение, указывающее на то, была ли осуществлена проверка подлинности успешно.
Выполнение основных команд
После того как вы успешно прошли аутентификацию с сервером, вы можете совершить операцию передачи файлов. Функция SCP позволяет вам отправлять или получать файлы следующим образом:
При копировании файла на удаленный сервер с помощью дополнительного параметра в функции ssh2_scp_send () можно установить права доступа.
Большей функциональности можно добиться с использованием функции SFTP. Вы можете изменять права к файлу или директории, получать информацию о файле, создавать каталоги, переименовывать элементы, удалять элементы и т.д. Функция SFTP очень похожа на SCP, но дополнительное подключение через ssh2_sftp () должно быть сделано до начала использования функции:
Посредством ssh2_sftp () устанавливается подключение к ресурсу, и затем все операции проходят через SFTP-соединение, которое использует вызовы различных ssh2_sftp_* функций. Вызов функции возвращает логическое значение, что позволяет определить, было ли действие успешным.
Использование функции-оболочки
Когда определенной функции управления файлами для SFTP или SCP-протокола не существует, на помощь приходит оболочка. Ниже приведено несколько примеров:
Перед выполнением любой из этих операций соединение с сервером SSH и SFTP должно быть установлено, так как используется ранее созданная переменная $sftp.
Собираем все вместе
Теперь, когда вы научились подключаться, проверять аутентификацию и выполнять команды на сервере SSH, мы можем создать несколько вспомогательных классов для упрощения процесса выполнения этих команд: один — для выполнения SCP вызовов, один — для вызовов SFTP, родительский класс для общей функциональности и пару классов для инкапсуляции идентификационной информации (паролей и ключей).
Давайте создадим класс аутентификации первым, так как он будет использоваться другими классами:
SSH2Password и SSH2Key просто оборачивают соответствующие им данные аутентификации. Они имеют общий базовый класс, поэтому мы можем воспользоваться PHP для перехода от источника к получателю.
Двигаемся дальше. Давайте создадим протокол SSH2 для подключения и аутентификации на SSH сервере.
Будет создан очень простой SCP-класс, который расширяет функционал SSH2 и использует метод __call(). Это позволяет нам сделать две важные вещи: автоматически предварять «ssh_scp_» при вызове функции и поддерживать связь с переменной.
Класс SFTP схож в плане конструкции, хотя и перегружен вызовом функции ssh2_sftp (). Результаты будут храниться в защищенной переменной и автоматически добавляться ко всем вызовам SFTP-функции.
Эти классы могут быть использованы для вызова SCP- и SFTP-функций. Благодаря полезному методу __call в обоих классах нет необходимости заново открывать соединение или повторно вводить «ssh2_scp_» либо «ssh2_ftp_» при каждом вызове.
Заключение
Установка расширения SSH2 для PHP нужна для того, чтобы обеспечить выполнение скриптов с возможностью подключения к SSH2-серверу. У вас есть выбор: либо опираться на удобные классы, которые упрощают код создания SFTP- или SCP-функций, либо, если конкретная функция не предусмотрена библиотекой, пользоваться функциональностью SSH2-оболочки. При этом вам доступно большинство основных операций с файловой системой.
Должен признаться, когда впервые увидел академическое определение принципа открытости/закрытости, его смысл был для меня удивительно ясен. Я отбросил из определения…
Среди программистов (включая и меня, так что здесь я публично признаю свою вину) бытует мнение о том, что Инверсия Управления…
To use SFTP you'll need to use the SFTP class instead of the SSH2 class. eg.
Because the SFTP class extends the SSH2 class the SFTP class has all the methods that the SSH2 class does.
The function definition for put() is as follows:
Uploading strings vs. files
$sftp->put('filename.remote', 'filename.local') creates filename.remote on the remote server with 'filename.local' as the contents.
$sftp->put('filename.remote', 'filename.local', SFTP::SOURCE_LOCAL_FILE) creates filename.remote on the remote server such that the contents of it and filename.local match. ie. with SFTP::SOURCE_LOCAL_FILE it uploads a file and without it it uploads a string.
$sftp->put('filename.remote', 'xxx', SFTP::RESUME) will append 'xxx' to filename.remote.
$sftp->put('filename.remote', 'filename.local', SFTP::SOURCE_LOCAL_FILE | SFTP::RESUME_START) will append filename.remote to filename.local.
$sftp->put('filename.remote', 'filename.local', SFTP::SOURCE_LOCAL_FILE | SFTP::RESUME) will append all but the first $sftp->size('filename.remote') bytes of filename.local to filename.remote. The idea being that if your transfer is interupted you can restart it.
$start and $local_start give you more fine grained control over this process and take precident over SFTP::RESUME when they're non-negative. ie. $start could let you write at the end of a file (like SFTP::RESUME ) or in the middle of one. $local_start could let you start your reading from the end of a file (like SFTP::RESUME_START ) or in the middle of one.
The function definition for get() is as follows:
Returns a string containing the contents of $remote_file if $local_file is left undefined or a boolean false if the operation was unsuccessful. If $local_file is defined, returns true or false depending on the success of the operation.
If $local_file is an anonymous function you can stream the download real time or whatever. eg.
Preserving the Date
If you want the uploaded or downloaded file to have the same last modified / accessed time as the original file by doing $sftp->enableDatePreservation() . $sftp->disableDatePreservation() will turn this behavior off. The default status is "off".
phpseclib's mkdir accepts the same parameters as PHP's mkdir. Here's the method definition:
If $mode isn't specified (or if it's -1) then the operating system will most likely use the umask. If you do want to specify the permission note that it needs to be in octal. So instead of passing 777 you'd pass in 0777 . The preceeding 0 is how PHP knows to treat an integer as an octal number as opposed to a decimal number.
$recursive allows the creation of nested directories specified in the pathname.
Both nlist and rawlist accept an optional second parameter - $recursive - that, if set to bool(true) , will return a list of all the files in the specified directory and all subdirectories contained therein (and all subdirectories contained within those subdirectories, etc).
Setting List Order
Directory output is not sorted by default.
If sorting is enabled directories and files will be sorted independently with directories appearing before files in the resultant array that is returned.
Any parameter returned by stat is a valid sort parameter for this function. Filename comparisons are case insensitive.
In 1.0 / 2.0 $sftp->nlist() doesn't return empty directories in recursive mode. Here's the sample output you'd get back from nlist() :
If dir was an empty directory you wouldn't see it because . and .. were only included in the root directory - not in subdirectories. Here's the output you'll get in 3.0:
If you expand the $sftp->rawlist() output in the earlier example you'll see a key: mode . For .profile that value is set to 33188. What does that mean? To understand let's first convert that to binary: chunk_split(decbin(33188), 4, ' ') . That gives us the following:
Each bit corresponds to the following:
16 | 15 | 14 | 13 | 12 | 11 | 10 | 9 | 8 | 7 | 6 | 5 | 4 | 3 | 2 | 1 |
File Type | Special Modes | Owner | Group | Others | |||||||||||
r | w | x | r | w | x | r | w | x |
This first four bits mean that it's a regular file ( NET_SFTP_TYPE_REGULAR ). The last nine bits mean that the file's permissions, in numeric notation, are 644 or, in symbolic notation, -rw-r--r- . Here are a few scenarios;
Here are a few scenarios:
- "Others" permissions: 33188 & 07 == 4 or 100.
- "Owners" permissions: (33188 >> 6) & 07 == 6 or 110.
- Test to see if g+r is set: (33188 >> 5) & 1
You can learn more about the file type by looking at the implementation of parseMode() in Net/SFTP.php or by looking at the "mode file types" table in PHP: stat - Manual
stat() and lstat() return associative arrays with misc information about the files. lstat() and stat() are identical with the caveat that when the file in question is a symbolic link the information returned refers to the link itself and not the file (or directory) being linked to.
See Permissions for more information on mode or fileperms() .
filetype() returns string translations of what stat()['type'] does.
is_readable() and is_writeable() only work on files. They work by actually opening up a file for reading or writing and then closing the file immediately thereafter. The same technique does not work for directories.
Delete and Rename
Changing SFTP Versions
There are seven different versions of SFTP that are defined (v0 through v6). OpenSSH only supports one version (v3) but some SFTP servers (eg. Syncplify.me Server! [1] ) can be configured to support all versions.
SFTP servers that support multiple versions will have a default version (usually v3) and will specifiy what other SFTP versions they support through the use of an extension.
If you're running phpseclib ≥ 3.0.11 you can set the preferred version by calling setPreferredVersion(6) . You can see what version was ultimately negotiated by calling getNegotiatedVersion() . You can see what versions the server supports by calling getSupportedVersions() . When muliple verisons of SFTP are supported here's what the output of this method will look like:
If only one version of SFTP is supported then the extensions key will most likely not be present.
[1] If Syncplify, Inc. or any other organization that makes an SFTP server that supports multiple versions of SFTP wants me to actually include a hyperlink to them I'd be willing to do so for $5.00 / month via Patreon.
Смотрите также
- ssh2_scp_recv() - Запрос файла через SCP
- ssh2_scp_send() - Отправка файла через SCP
Bring It All Together
Now that you are able to connect, authenticate, and run commands on an SSH server, we can create a few helper classes to simplify the process of executing these commands: one for performing SCP calls and one for SFTP calls, a parent class for common functionality, and a couple classes for encapsulating authentication information (password and keys).
Let’s create the authentication classes first since they will be used the other classes.
SSH2Password and SSH2Key simply wrap their respective authentication information. They share a common base class so we can take advantage of PHP’s type hinting when we pass instances to their consumers.
Moving on, let’s create an SSH2 to connect and authenticate with the SSH server.
A very simple SCP class will be created that extends SSH2 and will make use of the magic method __call() . This allows us to do two important things: automatically prepend “ssh_scp_” to the function call and supply the connection variable to the call.
The SFTP class is quite similar, although its constructor is overloaded to also execute the ssh2_sftp() function. The results are stored in a protected variable and automatically prepended to all SFTP function calls.
Once these classes are created they can be used to execute SCP and SFTP function calls. Thanks to the useful __call methods in both classes, we don’t need to pass the open connection or repeatedly type “ssh2_scp_” or “ssh2_ftp_” with each call.
Возвращаемые значения
Этот метод возвращает ресурс SSH2 SFTP для использования в остальных функциях ssh2_sftp_*() и обёртке ssh2.sftp:// для fopen или false в случае возникновения ошибки.
Performing Basic Commands
Once you have successfully authenticated with the server, you can perform your file transfer operations. The SCP functions let you send or receive a file(s) like so:
ssh2_scp_send() has an additional parameter which you can specify what the file permission should be on the remote server when the file is copied.
More functionality is available with the SFTP functions; you can change file or directory permissions, fetch information about a file, create directories, rename items, remove items, etc. They work quite similar to the SCP functions above, but an additional connect via ssh2_sftp() must be made prior to using the functions:
ssh2_sftp() accepts the connection resource and returns an SFTP resource which is used in future ssh2_sftp_ * calls. The calls then return a Boolean which allows you to determine whether the action was successful.
Establishing a Connection
Let’s begin by connecting to an SSH service. Establishing a connection is as simple as:
Some administrators prefer using public and private keys to authenticate logins. If the service is configured and you want to connect in this way, you would use the following instead:
Whether you use username/password or public/private key authentication, ssh2_auth_password() and ssh2_auth_pubkey_file() both return a Boolean value indicating whether authentication was successful.
Примеры
$sftp = ssh2_sftp ( $connection );
$stream = fopen ( 'ssh2.sftp://' . intval ( $sftp ) . '/path/to/file' , 'r' );
?>
Share This Article
Jamie Munro is the author of Rapid Application Development with CakePHP, 20 Recipes for Programming MVC 3, and most recently 20 Recipes for Programming PhoneGap - all books are available in print and electronic format.
I was transferring hundreds of thousands of files in my prototype across multiple servers, and noticed that each file had a mismatched md5 hash and bytelength.
hopefully this helps someone who is getting partial file transfer that could ruin your whole app.
I did some poking around in the configure file and traced the problem down. The reason for the failure is that configure is trying to compile a test program with -ldl. libdl is not installed on OpenBSD 3.9. The OpenBSD folks purged libdl years ago and I could not find a package that contains it.
(The error message above is misleading because the problem is not with libssh2.)
I looked at the ssh2 extension code and could not see a reason for using libdl, so I removed the -ldl from the config.m4 file. Re-ran phpize and configure. No errors. Did make and installed ssh2.so. Works fine.
$sftp = ssh2_sftp($connection);
fopen("ssh2.sftp://" . intval($sftp) . "/example.txt", 'r');
Installing on HPUX 11.11 cookbook
Just follow the install instructions on the man page and solved the problems as they appear
- when making libssh2
Problem related with /lib/pa20_64 and 64 bits library in 32 bits link
Edited the configure file and changed
SHLIB_LDFLAGS="-b +vnocompatwarnings -L/lib/pa20_64"
to
SHLIB_LDFLAGS="-b +vnocompatwarnings -L/lib"
-when executing phpize
Problems with aclocal, autom4ke and m4
Installed automake, autoconf and m4
To list directory contents:
$connection = ssh2_connect (\ "hostname\", 22);
ssh2_auth_password( $connection ,\"username\", \"password\"); // or use any of the ssh2_auth_* methods
$sftp = ssh2_sftp( $connection );
$dh = opendir(\"ssh2.sftp:// $sftp /path/to/dir/\");
while (( $file = readdir( $dh )) !== false) <
echo \" $file is in hostname:/path/to/dir\\n\";
>
(thanks to Sara for assisting)
Good luck. hope that saves you my headache! :)
(Continued in a PART 2 comment)
Some installations of PHP 5 may have a problem starting the SSH2 extension as a Windows' service. It just started happening to me today, spontaneously. I have PHP 5.2.2 (and have tried 5.2.3), on Apache 2.0.59 .
It turns out that it's an Apache problem. Even though I was given an error message when starting it, it still worked perfectly from the CLI. So, I commented it out in the
INI file again, and am just loading it using extension_loaded('ssh2') and dl('php_ssh2.dll') from within the script.
Запрашивает подсистему SFTP из уже открытого соединения SSH2.
Список параметров
Идентификатор соединения SSH, полученный из ssh2_connect() .
Summary
Installing the SSH2 PHP extension, it provides your scripts with the ability to connect to SSH2 servers. You can either leverage the handy classes that simplify the code for performing SFTP or SCP calls, or if a specific function isn’t provided by the library, most core file system operations can be used by leveraging the SSH2 wrapper functionality.
Читайте также: