php用ftp_put上传图片文件失败,文件大小为0

485 阅读1分钟

本文已参与「新人创作礼」活动,一起开启掘金创作之路。

php 封装了个ftp上传类,其中upload方法调用 ftp_put上传图片文件,之前用的windows服务器用了2年多没有问题,前阵子换了linux服务器后一直没有注意这个问题,最近客户端有反应图片上传不成功。

从接口接收到客户端传递来的数据开始一步步中断测试,最终问题定位在了Ftp类中的upload方法里,这里面 ftp_put(this>conn,this->conn,remote_file,localfile,local_file,mode)一直返回false,但是查看ftp服务器中图片文件却是传进去了,只不过文件大小为0,这就难搞了,ftp服务器,web服务器中相关文件夹权限都为777,异步和同步测试完,都不行,折腾了六七个小时没搞定,

最终是查到一点资料,ftp服务器主动/被动模式切换,tp_pasv($this->link,true) 切换到被动模式,客户端上传文件了成功,暂时先不细究原因了,先记录下以后有时间再慢慢研究。

下面是我Ftp类中的upload方法:

/**
 * 上传文件到ftp服务器
 * @param string $local_file 本地(接口临时目录)文件路径
 * @param string $remote_file 远程(图片服务器)文件地址
 * @param string $mode 上传模式(ascii和binary其中之一)
 * @return boolean
 */
public function upload($local_file='',$remote_file='',$mode='auto',$permissions=NULL){
    if ( ! file_exists($local_file)){
        $this->error = "本地文件不存在";
        return FALSE;
    }
    if ($mode == 'auto'){
        $ext = $this->_get_ext($local_file);
        $mode = $this->_set_type($ext);
    }
    
    $this->_create_remote_dir($remote_file); // 创建文件夹
     $mode = ($mode == 'ascii') ? FTP_ASCII : FTP_BINARY;
    ftp_pasv($this->conn,true); // 注:切换到被动模式,否则linux服务器下上传图片文件大小为0
    $result = @ftp_put($this->conn,$remote_file,$local_file,$mode);
    // var_dump($result);
    if ($result === FALSE){
        $this->error = "文件上传失败";
        return FALSE;
    }
    return TRUE;
}