【PHP】php實現ftp傳輸文件


1、linux服務器安裝vsftpd,參考我的另一篇文章:https://www.cnblogs.com/xuzhengzong/p/8645908.html

2、ftp安裝完畢,php引入ftp類,參考:https://www.cnblogs.com/phproom/p/9683612.html

laravel5上代碼,控制器:

/**
    * ftp發送文件至linux服務器
    * @param : $local_file 本地地址使用絕對地址;$remote_file遠程地址,(ftp用戶home地址/home/ftpuser省略,如實際地址為/home/ftpuser/pub/2021/a.txt,我們只需要傳'pub/2021/a.txt')
    * @return : bool
    * date: xzz 2021年1月26日下午2:51:55
    */
    public function FileFtpToOMS( $local_file, $remote_file ) : bool
    {
        try {
            //declare(strict_types=1);
            $config = config('cache.fpOMS.omsFtp');
            $ftp = new Ftp($config);
            $result = $ftp->connect();
            if ( ! $result){
                log_write("fail-ftp連接失敗,msg={$ftp->get_error_msg()}");
                //echo("fail-ftp連接失敗,msg={$ftp->get_error_msg()}");
                $ftp->close();
                return false;
            }
            //上傳文件
            if ($ftp->upload($local_file, $remote_file)){
                log_write("success-ftp上傳對賬單成功");
                //echo("success-ftp上傳對賬單成功");
            }else{
                log_write("fail-ftp上傳對賬單失敗,msg={$ftp->get_error_msg()}");
                //echo("fail-ftp上傳對賬單失敗,msg={$ftp->get_error_msg()}");
            }
/*             //刪除文件
            if ($ftp->delete_file($remote_file)){
                echo "刪除成功";
            }else{
                echo "刪除失敗";
            }
            
            //刪除整個目錄
            $remote_path='2018-09-19';
            if ($ftp->delete_dir($remote_path)){
                echo "目錄刪除成功";
            }else{
                echo "目錄刪除失敗";
            }
            
            //下載文件
            $local_file2 = 'video5.mp4';
            $remote_file2='video3.mp4';
            if ($ftp->download($local_file2,$remote_file2)){
                echo "下載成功";
            }else{
                echo "下載失敗";
            }
            
            //移動文件|重命名文件
            $local_file3 = 'video3.mp4';
            $remote_file3='shangchuan3/video3.mp4';
            if ($ftp->remane($local_file3,$remote_file3)){
                echo "移動成功";
            }else{
                echo "移動失敗";
            } */
            
            $ftp->close();
        }catch (\Exception $e){
            log_write("fail-ftp上傳對賬單異常,msg={$e->getMessage()}");
            //echo("fail-ftp上傳對賬單異常,msg={$e->getMessage()}");
            UpPayOrderDao::sendEmail("fail-ftp上傳對賬單異常".date('Y-m-d H:i:s'), $e->getMessage());
            return false;
        }
        return true;
    }

ftp類:(引入記得 composer dump-autoload)

<?php
/**
 * Created by PhpStorm.
 * User: 123456
 * Date: 2018/9/20
 * Time: 11:15
 * @author sunjiaqiang
 * @email 1355049422@qq.com
 */
namespace Lib\PublicClass;

class Ftp{
        private $host='';//遠程服務器地址
        private $user='';//ftp用戶名
        private $pass='';//ftp密碼
        private $port=21;//ftp登錄端口
        private $error='';//最后失敗時的錯誤信息
        protected $conn;//ftp登錄資源

        /**
         * 可以在實例化類的時候配置數據,也可以在下面的connect方法中配置數據
         * Ftp constructor.
         * @param array $config
         */
        public function __construct(array $config=[])
        {
            empty($config) OR $this->initialize($config);
        }

        /**
         * 初始化數據
         * @param array $config 配置文件數組
         */
        public function initialize(array $config=[]){
            $this->host = $config['host'];
            $this->user = $config['user'];
            $this->pass = $config['pass'];
            $this->port = isset($config['port']) ?: 21;
        }

        /**
         * 連接及登錄ftp
         * @param array $config 配置文件數組
         * @return bool
         */
        public function connect(array $config=[]){
            empty($config) OR $this->initialize($config);
            if (FALSE == ($this->conn = @ftp_connect($this->host))){
                $this->error = "主機連接失敗";
                return FALSE;
            }
            if ( ! $this->_login()){
                $this->error = "服務器登錄失敗";
                return FALSE;
            }
            return TRUE;
        }

        /**
         * 上傳文件到ftp服務器
         * @param string $local_file 本地文件路徑
         * @param string $remote_file 服務器文件地址
         * @param bool $permissions 文件夾權限
         * @param string $mode 上傳模式(ascii和binary其中之一)
         */
        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;
            $result = @ftp_put($this->conn,$remote_file,$local_file,$mode);//同步上傳
            if ($result === FALSE){
                $this->error = "文件上傳失敗";
                return FALSE;
            }
            return TRUE;
        }

        /**
         * 從ftp服務器下載文件到本地
         * @param string $local_file 本地文件地址
         * @param string $remote_file 遠程文件地址
         * @param string $mode 上傳模式(ascii和binary其中之一)
         */
        public function download($local_file='',$remote_file='',$mode='auto'){
            if ($mode == 'auto'){
                $ext = $this->_get_ext($remote_file);
                $mode = $this->_set_type($ext);
            }
            $mode = ($mode == 'ascii') ? FTP_ASCII : FTP_BINARY;
            $result = @ftp_get($this->conn, $local_file, $remote_file, $mode);
            if ($result === FALSE){
                return FALSE;
            }
            return TRUE;
        }

        /**
         * 刪除ftp服務器端文件
         * @param string $remote_file 文件地址
         */
        public function delete_file(string $remote_file=''){
            $result = @ftp_delete($this->conn,$remote_file);
            if ($result === FALSE){
                return FALSE;
            }
            return TRUE;
        }
        /**
         * ftp創建多級目錄
         * @param string $remote_file 要上傳的遠程圖片地址
         */
        private function _create_remote_dir($remote_file='',$permissions=NULL){
            $remote_dir = dirname($remote_file);
            $path_arr = explode('/',$remote_dir); // 取目錄數組
            //$file_name = array_pop($path_arr); // 彈出文件名
            $path_div = count($path_arr); // 取層數
            foreach($path_arr as $val) // 創建目錄
            {
                if(@ftp_chdir($this->conn,$val) == FALSE)
                {
                    $tmp = @ftp_mkdir($this->conn,$val);//此處創建目錄時不用使用絕對路徑(不要使用:2018-02-20/ceshi/ceshi2,這種路徑),因為下面ftp_chdir已經已經把目錄切換成當前目錄
                    if($tmp == FALSE)
                    {
                        echo "目錄創建失敗,請檢查權限及路徑是否正確!";
                        exit;
                    }
                    if ($permissions !== NULL){
                        //修改目錄權限
                        $this->_chmod($val,$permissions);
                    }
                    @ftp_chdir($this->conn,$val);
                }
            }

            for($i=0;$i<$path_div;$i++) // 回退到根,因為上面的目錄切換導致當前目錄不在根目錄
            {
                @ftp_cdup($this->conn);
            }
        }

        /**
         * 遞歸刪除ftp端目錄
         * @param string $remote_dir ftp目錄地址
         */
        public function delete_dir(string $remote_dir=''){
            $list = $this->list_file($remote_dir);
            if ( ! empty($list)){
                $count = count($list);
                for ($i=0;$i<$count;$i++){
                    if ( ! preg_match('#\.#',$list[$i]) && !@ftp_delete($this->conn,$list[$i])){
                        //這是一個目錄,遞歸刪除
                        $this->delete_dir($list[$i]);
                    }else{
                        $this->delete_file($list[$i]);
                    }
                }
            }
            if (@ftp_rmdir($this->conn,$remote_dir) === FALSE){
                return FALSE;
            }
            return TRUE;
        }

        /**
         * 更改 FTP 服務器上的文件或目錄名
         * @param string $old_file 舊文件/文件夾名
         * @param string $new_file 新文件/文件夾名
         */
        public function remane(string $old_file='',string $new_file=''){
            $result = @ftp_rename($this->conn,$old_file,$new_file);
            if ($result === FALSE){
                $this->error = "移動失敗";
                return FALSE;
            }
            return TRUE;
        }

        /**
         * 列出ftp指定目錄
         * @param string $remote_path
         */
        public function list_file(string $remote_path=''){
            $contents = @ftp_nlist($this->conn, $remote_path);
            return $contents;
        }

        /**
         * 獲取文件的后綴名
         * @param string $local_file
         */
        private function _get_ext($local_file=''){
            return (($dot = strrpos($local_file,'.'))==FALSE) ? 'txt' : substr($local_file,$dot+1);
        }

        /**
         * 根據文件后綴獲取上傳編碼
         * @param string $ext
         */
        private function _set_type($ext=''){
            //如果傳輸的文件是文本文件,可以使用ASCII模式,如果不是文本文件,最好使用BINARY模式傳輸。
            return in_array($ext, ['txt', 'text', 'php', 'phps', 'php4', 'js', 'css', 'htm', 'html', 'phtml', 'shtml', 'log', 'xml'], TRUE) ? 'ascii' : 'binary';
        }

        /**
         * 修改目錄權限
         * @param $path 目錄路徑
         * @param int $mode 權限值
         */
        private function _chmod($path,$mode=0755){
            if (FALSE == @ftp_chmod($this->conn,$path,$mode)){
                return FALSE;
            }
            return TRUE;
        }

        /**
         * 登錄Ftp服務器
         */
        private function _login(){
            return @ftp_login($this->conn,$this->user,$this->pass);
        }

        /**
         * 獲取上傳錯誤信息
         */
        public function get_error_msg(){
            return $this->error;
        }
        /**
         * 關閉ftp連接
         * @return bool
         */
        public function close(){
            return $this->conn ? @ftp_close($this->conn_id) : FALSE;
        }
}

 

效果:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM