php连接ftp

PHP连接ftp,发现一个很好用的类库phpseclib。英文原文

Connecting to SFTP with PHP

If you need to connect to SFTP using PHP then the simplest approach I’ve found is to use phpseclib, a library of functions for secure communications.

The library is a Composer package so you will need to have Composer installed, then just require the package as usual:-

$ composer require phpseclib/phpseclib

The library provides what it refers to as a “pure-PHP implementation of SFTP” and supports the most widely used versions of SFTP.

To initiate a connection a new object of SFTP is created with the address of the remote server passed to the constructor. To authenticate our SFTP connection we can pass the login credentials using SFTP::login():-

use phpseclib\Net\SFTP; 
$sftp = new SFTP('www.example.com'); 
if (!$sftp->login('username', 'password')) { throw new Exception('Login failed'); } 

If we’ve got a private key we need to use the RSA class so that we can pass the key in place of the password to the SFTP::login() method:-

use phpseclib\Crypt\RSA; use phpseclib\Net\SFTP; 
$sftp = new SFTP('www.example.com'); 
$Key = new RSA(); // If the private key has a passphrase we set that first $Key->setPassword('passphrase'); // Next load the private key using file_gets_contents to retrieve the key $Key->loadKey(file_get_contents('path_to_private_key')); 
if (!$sftp->login('username', $Key)) { throw new Exception('Login failed'); } 

The SFTP class provides methods for SFTP similar to those provided by PHP’s FTPextension. For example, to get a list of files for the current directory we usenlist() (equivalent of ftp_nlist):-

$files = $sftp->nlist(); 

To change directory use chdir():-

$sftp->chdir('directory_name'); 

To get a file from the remote server use get():-

$sftp->get('remote_file', 'local_file'); 

This saves the remote_file to local_file. If the second parameter is left empty then the method returns the contents of the remote file if successful (otherwise it returns false).

To upload a file to the remote server use put():-

$sftp->put('remote_file', 'contents for remote file'); 

There are many other methods available and can be found in the SFTP class. The class is well documented with thorough comments. The above methods should get you started though.

Hopefully you can see that phpseclib provides a simple way of working with aSFTP connection.

 

转载于:https://www.cnblogs.com/webclz/p/5123628.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值