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.

  • 相关阅读:
    hadoop-2.7.3安装kafka_2.11-2.1.0
    HBase数据快速导入之ImportTsv&Bulkload
    hbase shell 基本操作
    SQLplus命令中删除键和翻页键不能用的问题
    SQL*Loader 的使用sqlldr和sqluldr2方法详解
    python连接oracle导出数据文件
    python零碎知识点一
    用Python输出一个Fibonacci数列
    问题总结——window平台下gruntower安装后无法运行的问题
    JavaScript学习笔记——浅拷贝、深拷贝
  • 原文地址:https://www.cnblogs.com/webclz/p/5123628.html
Copyright © 2011-2022 走看看