好的,所以通过ftp或sftp从你自己访问其他服务器……我写了一个小类来处理它.它显然是新的,可以很容易地改进,所以我想把它扔出去看看其他人认为(stackoverflow得到了很多观点,所以希望这可以帮助其他人),以及他们如何改进它…所以我想问题是……如何改进?
class ftp_sftp{
//determine,if ssh,to use PHPseclib or PHP's inbuilt ssh_sftp 'libssh'
public $ssh_type = 'PHPseclib';
//set ths path to the directory containing the entire PHPseclib files
public $PHPseclib_path = 'scripts/PHPseclib0.3.0';

//private vars generated by this class
public $host;
public $username;
public $password;
public $connection_type;
public $port_number;
public $connection = false;

//contruct method which will attempt to set the connection details and automatically attempt to establisha connection to the server
public function __construct( $host,$username,$password,$connection_type,$port_number = false ){

    //add the webroot to the beginning of the $this->PHPseclib_path (this is bespoke to my own configuration)
    $this->PHPseclib_path = WEbroOT_PRIVATE.$this->PHPseclib_path;

    //setting the classes vars
    $this->host         = $host;
    $this->username     = $username;
    $this->password     = $password;
    $this->connection_type = $connection_type;

    //set the port number to defaults based on connection type if none passed
    if( $port_number === false ){
        if( $connection_type == 'ftp' ){
            $port_number = 21;
        } else {
            $port_number = 22;
        }
    }
    $this->port_number = $port_number;

    //Now set the server connection into this classes connection var
    $this->connection = $this->connect();
}

//tests the details passed and tries to establish a connection,returns false on fail.
function connect(){
    br($this->connection_type);
    switch( $this->connection_type )
        {
            case 'ftp':
                        $connection = ftp_connect($this->host);
                        $login = ftp_login($connection,$this->username,$this->password);

                        //if no connection was possible return false and leave $this-connection as false
                        if(!$connection || !$login){
                            return false;
                        } else {
                            // enabling passive mode
                            ftp_pasv( $connection,true );
                            return $connection;
                        }
            break;

            case 'sftp':
                        //decide which ssh type to use
                        switch( $this->ssh_type ){
                            case 'PHPseclib':
                                    //inlcude the PHPseclib path in the include array and include the ssh2 class
                                    set_include_path($this->PHPseclib_path );
                                    if(!include('Net/SSH2.PHP')){
                                        echo 'Sorry Failed to load SSH2 class';
                                        br();
                                    }
                                    if(!include('Net/SFTP.PHP')){
                                        echo 'Sorry Failed to load SFTP class';
                                        br();
                                    }

                                    $connection = new Net_SFTP($this->host,$this->port_number);
                                    $login = $connection->login($this->username,$this->password);
                            break;

                            case 'libssh2':
                                    $connection = ssh2_connect($this->host,$this->port_number);
                                    $login = ssh2_auth_password($connection,'username','secret');
                            break;

                            default:
                                    echo 'No ssh method defined,please define one in: $ftp_sftp->ssh_type';
                                    exit();
                            break;
                        }


                        //if no connection was possible return false and leave $this-connection as false
                        if (!$connection || !$login) {
                            return false;
                        } else {
                            return $connection;
                        }
            break;

            default: echo 'No connection type set cannot choose a method to connect';
            break;
        }
}

//acces the PHPseclib errors
public function errors(){
if($this->connection_type == 'sftp' && $this->ssh_type == 'PHPseclib'){
        print_r($this->connection->getErrors());
    } else {
        echo 'no error logs available';
    }
}

//function used by this class to check certain values are set
public function connection_check(){
    if( $this->connection === false){
        echo 'Sorry there seems to be a connection problem please try again';
        br();
    }

    if( $this->connection_type === false){
        echo 'Sorry there seems to be a no connection type set';
    }

    if( $this->connection === false || $this->connection_type === false ){
        exit();
    }
}

//transfers a file to the connected server
public function put($targetLocationToSendTo,$existingLocationToSendFrom){

    //check the connection
    $this->connection_check();

    switch( $this->connection_type )
        {
            case 'ftp':
                        //ftp_put the file across
                        $put = ftp_put( $this->connection,$targetLocationToSendTo,$existingLocationToSendFrom,FTP_BINARY);
            break;

            case 'sftp':
                        //decide which ssh type to use
                        switch( $this->ssh_type ){
                            case 'PHPseclib':
                                    $put = $this->connection->put( $targetLocationToSendTo,NET_SFTP_LOCAL_FILE );
                            break;

                            case 'libssh2':
                                    $put = ssh2_scp_send($this->connection,0755);
                            break;
                        }
            break;
        }

    return $put;
}

//list the contents of a remote directory
public function dir_list( $dirToList ){

    //check the connection
    $this->connection_check();

    //run appropriate list
    switch( $this->connection_type )
        {
            case 'ftp':
                        $list = $this->connection = ftp_nlist($this->connection,$dirToList);
            break;

            case 'sftp':
                        //decide which ssh type to use
                        switch( $this->ssh_type ){
                            case 'PHPseclib':
                                    $list = $this->connection->nlist( $dirToList );
                            break;

                            case 'libssh2':
                                    echo 'Sorry there is no support for nlist with libssh2,however this link has a possible answer: http://randomdrake.com/2012/02/08/listing-and-downloading-files-over-sftp-with-PHP-and-ssh2/';
                            break;
                        }
            break;
        }

    return $list;
}

//get the timestamp of the file on another server
public function remote_filemtime( $pathToFile ){

    //check the connection
    $this->connection_check();

    //run appropriate list
    switch( $this->connection_type )
        {
            case 'ftp':
                        $timeStamp = ftp_mdtm($this->connection,$pathToFile);
            break;

            case 'sftp':
                        //decide which ssh type to use
                        switch( $this->ssh_type ){
                            case 'PHPseclib':
                                    $statinfo = $this->connection->stat( $pathToFile );
                            break;

                            case 'libssh2':
                                    $statinfo = ssh2_sftp_stat($this->connection,$pathToFile);
                            break;
                        }

                        if($statinfo['mtime']){
                            $timeStamp = $statinfo['mtime'];
                        } else {
                            $timeStamp = false;
                        }
            break;
        }

    return $timeStamp;
}

//make a directory on the Remote Server
public function make_dir( $dirTomake ){
    //check the connection
    $this->connection_check();

    //run appropriate list
    switch( $this->connection_type )
        {
            case 'ftp':
                        $dir_made = ftp_mkdir($this->connection,$dirTomake);
            break;

            case 'sftp':
                        //decide which ssh type to use
                        switch( $this->ssh_type ){
                            case 'PHPseclib':
                                    $statinfo = $this->connection->mkdir( $dirTomake );
                            break;

                            case 'libssh2':
                                    $statinfo = ssh2_sftp_mkdir($this->connection,$dirTomake,0755);
                            break;
                        }
            break;
        }

    return $dir_made;
}

//change directory
public function change_dir( $dirToMoveto ){
    //check the connection
    $this->connection_check();

    //run appropriate list
    switch( $this->connection_type )
        {
            case 'ftp': $chdir = ftp_chdir($this->connection,$dirToMoveto );
            break;

            case 'sftp':
                        //decide which ssh type to use
                        switch( $this->ssh_type ){
                            case 'PHPseclib':
                                    $chdir = $this->connection->chdir( $dirToMoveto );
                            break;

                            case 'libssh2':
                                    echo 'Sorry this feature does exist yet for when using libssh2 with the ftp_sftp class';
                                    exit();
                            break;
                        }
            break;
        }

    return $chdir;
}

//curent directory we are looking in
public function pwd(){

    //check the connection
    $this->connection_check();

    //run appropriate list
    switch( $this->connection_type )
        {
            case 'ftp': $pwd = ftp_pwd($this->connection);
            break;

            case 'sftp':
                        //decide which ssh type to use
                        switch( $this->ssh_type ){
                            case 'PHPseclib':
                                    $pwd = $this->connection->pwd();
                            break;

                            case 'libssh2':
                                    echo 'Sorry this feature does exist yet for when using libssh2';
                                    exit();
                            break;
                        }
            break;
        }

    return $pwd;
}

//delete file
public function delete_file($filetoDelete){
    //check the connection
    $this->connection_check();

    //run appropriate list
    switch( $this->connection_type )
        {
            case 'ftp': $unlink = ftp_delete($this->connection,$filetoDelete);
            break;

            case 'sftp':
                        //decide which ssh type to use
                        switch( $this->ssh_type ){
                            case 'PHPseclib':
                                    $unlink = $this->connection->delete( $filetoDelete );
                            break;

                            case 'libssh2':
                                    $unlink = ssh2_sftp_unlink($this->connection,$filetoDelete);
                            break;
                        }
            break;
        }

    return $unlink;
}   }//end of class

使用课程:

$ftp_sftp = new ftp_sftp( '92.21.627.163','ftpuser','yourpassword','','ftp','21' );
echo $ftp_sftp->pwd();

我在使用easyPHP连接我的win7机器上的PHPseclib时遇到了一些麻烦,并开始了Q ..如果有人有任何想法我会非常感激…
Cannot get phpseclib to connect – error 10060

这段代码的主要问题是它垂直缩放.假设您决定添加另一个实现,一个本地文件系统,为$file_type的’file’引入第三个潜在值.现在你必须通过代码添加案例’文件’:各地的条件,使ftp_sftp失去控制.你现在在’sftp’代码分支中再次遇到同样的问题,处理$ssh_type.

原始代码

switch($connection_type) {
    case 'ftp'  : // ...
    case 'stfp' : // ...
}

switch($connection_type) {
    case 'ftp'  : // ...
    case 'stfp' : // ...
    case 'file' : // ...
}

请记住,这是针对切换$connection_type的代码中的每个switch语句.想象一下,我们将多少行代码添加到ftp_sftp类中以合并每个附加行为……

事实上,你现在看起来实际上有三种策略,ftp,sftp& SSH.

你想要做的是将代码设置为水平扩展而不是垂直扩展,这样做的方法是通过Strategy design pattern.

基本上你正在做的是在代码中拉出公共接口,然后为FTP和&创建单独的实现. SFTP.有很多不同的方法可以对此进行实际实施,因此请调整您心中的内容!

一个通用的界面

这是任何’ftp类’必须能够做的定义.

interface PHPFtp
{
    public function __construct($host,$port_number = false);
    public function connect();
    public function errors();
    public function connection_check();
    public function put($targetLocationToSendTo,$existingLocationToSendFrom);
    public function dir_list( $dirToList );
    public function remote_filemtime( $pathToFile );
    public function make_dir( $dirTomake );
    public function change_dir( $dirToMoveto );
    public function pwd();
    public function delete_file($filetoDelete);
}

一个工厂

现在整个代码中都有一个switch语句来检查$connection_type.您可能决定以不同方式处理默认情况.

class PHPFtpFactory
{
    public static function create($connection_type)
    {
        switch($connection_type) {
            case 'ftp':
                $oFtp = new Ftp();
                break;
            case 'sftp':
                $oFtp = new Sftp();
                break;
            default:
                throw new UnexpectedValueExcpetion(
                    'No connection type set cannot choose a method to connect');
        }

        // Potential follow-up construction steps
        return $oFtp;
    }
}

基类

不是绝对必要,但非常有帮助.此外,我们在这里偷偷摸摸另一个设计模式,称为Template Method.BaseFtp :: pwd是一个模板方法,它控制整个pwd算法,但委托给具体的孩子一部分.

abstract class BaseFtp implements PHPFtp
{
    public function pwd()
    {
        $this->connection_check();
        return $this->_pwd();
    }

    abstract protected function _pwd();
}

具体的FTP实现

现在我们有一个简洁的ftp类,它只进行FTP操作,它对SFTP一无所知.

class Ftp extends BaseFtp
{
    protected function _pwd()
    {
        return ftp_pwd($this->connection);
    }

    public function connect()
    {
        $connection = ftp_connect($this->host);
        $login      = ftp_login($connection,$this->password);

        // if no connection was possible return false and leave $this-connection as false
        if(!$connection || !$login)
            return false;

        // enabling passive mode
        ftp_pasv( $connection,true );
        return $connection;
    }
}

具体Sftp类

现在我们有一个独立的Sftp类,但是请注意它就像原始的ftp_sftp类为$connection_type做的那样切换$ssh_type.一旦你掌握了战略模式,并拥有Ftp&完成Sftp类后,您可以返回并在Sftp实现中实现策略模式,这样您就可以拥有2个类PHPseclib&例如,Libssh2.

class Sftp extends BaseFtp
{
    protected function _pwd()
    {
        // decide which ssh type to use
        switch($this->ssh_type) {
            case 'PHPseclib':
                return $this->connection->pwd();

            case 'libssh2':
                echo 'Sorry this feature does exist yet for when using libssh2';
                return false;
        }
    }

    public function connect()
    {
        // decide which ssh type to use
        switch( $this->ssh_type ) {
            case 'PHPseclib':
                // inlcude the PHPseclib path in the include array
                // and include the ssh2 class
                set_include_path($this->PHPseclib_path );
                if(!include('Net/SSH2.PHP')){
                    echo 'Sorry Failed to load SSH2 class';
                    br();
                }
                if(!include('Net/SFTP.PHP')){
                    echo 'Sorry Failed to load SFTP class';
                    br();
                }

                $connection = new Net_SFTP($this->host,$this->port_number);
                $login = $connection->login($this->username,$this->password);
                break;

            case 'libssh2':
                $connection = ssh2_connect($this->host,$this->port_number);
                $login = ssh2_auth_password($connection,'secret');
                break;

            default:
                echo 'No ssh method defined,please define one in: $ftp_sftp->ssh_type';
                exit();
                break;
        }

        if(!$connection || !$login)
            return false;
    }
}

使用新代码

随着新系统的到位,它的10X更容易看出是什么,每个类都关注它的特定领域,代码水平增长.那是什么意思?记住上面,当我们考虑在原始范例中添加第三个$connection_type’文件’时?在新的安排中,我们更新了一个switch语句,即工厂中的一个:

class PHPFtpFactory
{
    public static function create($connection_type)
    {
        switch($connection_type) {
            case 'ftp':
                $oFtp = new Ftp();
                break;
            case 'sftp':
                $oFtp = new Sftp();
                break;
            case 'file':
                $oFtp = new File();
                break;
            default:
                throw new UnexpectedValueExcpetion(
                    'No connection type set cannot choose a method to connect');
        }

        // Potential follow-up construction steps
        return $oFtp;
    }
}

然后你当然添加了新的具体实现

class File extends PHPFtp
{
    // ...
}

由于新的File类可以进入它自己的空间,我们不会扩展一个中心类,即原始的ftp_sftp类.

为了使用新系统,你可以在工厂找到一个实例并从那里开始

// get an instance of the Ftp class
$ftp  = PHPFtpFactory::create('ftp');

// get an instance of the Sftp class 
$sftp = PHPFtpFactory::create('sftp');

这些实例中的任何一个都支持所有PHPFtp函数,因为它们实现了接口!这也使您能够编写多态代码.考虑一个对接口进行类型提示的函数

// This is polymorphic code
function doFtpStuff(PHPFtp $oFtp) {
   // As mentioned above $oFtp can be an instance of any class that implements PHPFtp
   $oFtp->connect();
   $oFtp->pwd();
}

PHP FTP / SFTP交换机类的更多相关文章

  1. osx – 无法创建目录/ var / teamsserver

    OpenSSH_6.2p2,OSSLShim0.9.8r8Dec2011debug1:Readingconfigurationdata/etc/ssh_configdebug1:/etc/ssh_configline20:Applyingoptionsfor*debug1:Connectingto1.2.3.4[1.2.3.4]portPORT.debug1:Connectionestablished.Couldnotcreatedirectory‘/var/teamsserver/.ssh’.debug

  2. ios – Xcode Server 4.0 git从构建触发脚本推送

    我为一个托管在github上的项目安装了一个XcodeBot.我按照步骤和设置机器人来使用我现有的SSH密钥.验证成功,项目结算和建立.然后,我在预触发器操作中添加了一个shell脚本,它增加了plist中的版本,将其标记,并将该更改提交到github.但是当我尝试从shell脚本执行gitpush时,我得到:–推送到git@github.com:spex-app/spex-ios.git权限被拒

  3. ios – Xcode上传错误:无法打开ssh会话. (16)

    注意:我们终于上传了该应用程序,但是我们并没有真正解决这个问题,所以如果有人可以分享一些有关这个问题的宝贵意见或经验,我将不胜感激.我也检查了以下2个类似的问题,但这些没有帮助:>Erroruploadingiosapplicationtoitunesconnect“failedtoopensshsession(16)”>AppStoresubmission/distributionerror“f

  4. ios FTP使用NSURLSession上传

    我试图通过FTP将文件上传到服务器.根据NSK的NSURLSession类支持FTP操作.有一个着名的AppleDeveloperblog也支持.但还不清楚NSURLSessionAPI是否支持ftp上传?

  5. ios – Objective-C中的混合或多重继承?

    换句话说,是否可以创建一个可以从这两个子类继承的抽象类,然后只覆盖两者之间不同的方法?我到目前为止所知道的>我知道Objective-C不支持多重继承>我知道我可以使用Categories添加常用的方法,但是我不认为这会解决覆盖init方法或添加私有属性解决方法建立在Amin的答案上,这是怎么做的呢?

  6. 从iOS应用程序发送帖子到PHP脚本不工作…简单的解决方案就像

    我之前已经做了好几次了但是由于某些原因我无法通过这个帖子…我尝试了设置为_POST且没有的变量的PHP脚本……当它们未设置为发布时它工作精细.这是我的iOS代码:这里是PHP的一大块,POST变量不在正确的位置?我想这对于更有经验的开发人员来说是一个相当简单的答案,感谢您的帮助!解决方法$_POST是一个数组,而不是一个函数.您需要使用方括号来访问数组索引:

  7. swift详解之二十--------在xcode中使用git管理源代码,将代码提交到github

    在xcode中使用git管理源代码,将代码提交到github本文记录一下如何在Xcode中使用Git作为源代码控制工具,以及如何将本地的Git仓库和远程Github上的仓库集成起来,虽然这章节和swift没有关系,但我还是放在这里。对详细的git操作可以看在Xcode中使用Git进行源码控制讲得很详细,很好。将xcode与github链接起来。

  8. Swift 调用 objc/runtime OBJC_ASSOCIATION_RETAIN

    我扩展一些类在Swift2.0工作与ReactiveCocoa3.0,但遇到了一些问题。我跟随科林·艾伯哈特的教程,和有复制粘贴一些他UIKit扩展逻辑结束对我的OSX应用程序。它所有的编译很好,除了此属性:UInt,这给了我以下的编译器错误。使用的未解析的标识符如何访问此属性?我一直对importObjectiveC和#import头文件,但没有什么似乎工作。解决方法1:这是实际上现在导入Swift作为枚举命名为objc_AssociationPolicy。或与枚举速记语法。

  9. swift学习2 元组 tuples

    swift中出现了一种新的数据结构,非常牛掰的元组tuples如果懂PHP的猿,会发现这个元组和PHP的数组非常类似,同样是可以默认不指定key,也可以指定key目前的学习疑问是,如何进行元组的遍历?

  10. [快速学会Swift第三方库] SwiftyJSON篇

    [快速学会Swift第三方库]SwiftyJSON篇SwiftyJSON使得用Swift处理JSON数据更加容易。这是解析JSON字符串封装类。目录快速学会Swift第三方库SwiftyJSON篇目录编码之前导入SwiftyJSON其他操作解析本地JSON示例JSON示例代码运行结果解析网络JSON示例JSON示例代码运行结果深入学习编码之前导入SwiftyJSON推荐使用CocoaPods进行导入,CocoaPods是一个负责管理iOS项目中第三方开源库的工具,安装CocoaPods之后使用命令行就能轻

随机推荐

  1. PHP个人网站架设连环讲(一)

    先下一个OmnihttpdProffesinalV2.06,装上就有PHP4beta3可以用了。PHP4给我们带来一个简单的方法,就是使用SESSION(会话)级变量。但是如果不是PHP4又该怎么办?我们可以假设某人在15分钟以内对你的网页的请求都不属于一个新的人次,这样你可以做个计数的过程存在INC里,在每一个页面引用,访客第一次进入时将访问时间送到cookie里。以后每个页面被访问时都检查cookie上次访问时间值。

  2. PHP函数学习之PHP函数点评

    PHP函数使用说明,应用举例,精简点评,希望对您学习php有所帮助

  3. ecshop2.7.3 在php5.4下的各种错误问题处理

    将方法内的函数,分拆为2个部分。这个和gd库没有一点关系,是ecshop程序的问题。会出现这种问题,不外乎就是当前会员的session或者程序对cookie的处理存在漏洞。进过本地测试,includes\modules\integrates\ecshop.php这个整合自身会员的类中没有重写integrate.php中的check_cookie()方法导致,验证cookie时返回的username为空,丢失了登录状态,在ecshop.php中重写了此方法就可以了。把他加到ecshop.php的最后面去就可

  4. NT IIS下用ODBC连接数据库

    $connection=intodbc_connect建立数据库连接,$query_string="查询记录的条件"如:$query_string="select*fromtable"用$cur=intodbc_exec检索数据库,将记录集放入$cur变量中。再用while{$var1=odbc_result;$var2=odbc_result;...}读取odbc_exec()返回的数据集$cur。最后是odbc_close关闭数据库的连接。odbc_result()函数是取当前记录的指定字段值。

  5. PHP使用JpGraph绘制折线图操作示例【附源码下载】

    这篇文章主要介绍了PHP使用JpGraph绘制折线图操作,结合实例形式分析了php使用JpGraph的相关操作技巧与注意事项,并附带源码供读者下载参考,需要的朋友可以参考下

  6. zen_cart实现支付前生成订单的方法

    这篇文章主要介绍了zen_cart实现支付前生成订单的方法,结合实例形式详细分析了zen_cart支付前生成订单的具体步骤与相关实现技巧,需要的朋友可以参考下

  7. Thinkphp5框架实现获取数据库数据到视图的方法

    这篇文章主要介绍了Thinkphp5框架实现获取数据库数据到视图的方法,涉及thinkPHP5数据库配置、读取、模型操作及视图调用相关操作技巧,需要的朋友可以参考下

  8. PHP+jquery+CSS制作头像登录窗(仿QQ登陆)

    本篇文章介绍了PHP结合jQ和CSS制作头像登录窗(仿QQ登陆),实现了类似QQ的登陆界面,很有参考价值,有需要的朋友可以了解一下。

  9. 基于win2003虚拟机中apache服务器的访问

    下面小编就为大家带来一篇基于win2003虚拟机中apache服务器的访问。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧

  10. Yii2中组件的注册与创建方法

    这篇文章主要介绍了Yii2之组件的注册与创建的实现方法,非常不错,具有参考借鉴价值,需要的朋友可以参考下

返回
顶部