zoukankan      html  css  js  c++  java
  • 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 phpseclibNetSFTP;
    
    $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 phpseclibCryptRSA;
    use phpseclibNetSFTP;
    
    $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.

  • 相关阅读:
    docker容器的时间同步
    Java中的各种bean对应的意义(VO,PO,BO,QO, DAO,POJO,DTO)
    Vue-admin工作整理(十九):从数字渐变组件谈第三方JS库Count-to的使用
    HTTP 方法:Get与Post分析
    Java核心知识盘点(三)- 框架篇-Spring
    Java核心知识盘点(二)- 缓存使用
    Java核心知识盘点(一)- 数据存储
    Java基础知识盘点(三)- 线程篇
    Java基础知识盘点(二)- 集合篇
    Java基础知识盘点(一)- 基础篇
  • 原文地址:https://www.cnblogs.com/webclz/p/5123628.html
Copyright © 2011-2022 走看看