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.

  • 相关阅读:
    神经网络——BP算法
    汉诺塔
    Clucene系列3--Clucene的代码组织结构
    Clucene系列2--Clucene专业术语
    j
    TF-IDF的定义及计算
    Python编程 从入门到实践 练习5-10 检查用户名
    判断输入的正整数是否为素数
    百钱百鸡问题
    打印由 * 号组成的菱形
  • 原文地址:https://www.cnblogs.com/webclz/p/5123628.html
Copyright © 2011-2022 走看看