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.

  • 相关阅读:
    调用系统相机导致照片旋转问题的修复
    JavaLearning:日期操作类
    PHP实现事件机制实例分析
    按下葫芦起了瓢
    win系统下的eclipse连接和使用linux上的hadoop集群
    利用gradle加入构建版本
    从设计到实现,一步步教你实现Android-Universal-ImageLoader-辅助类
    I帧、P帧和B帧的特点
    tcp_tw_recycle检查tcp_timestamps的内核代码
    OBS源码编译开发
  • 原文地址:https://www.cnblogs.com/webclz/p/5123628.html
Copyright © 2011-2022 走看看