0

0

php ftp ftp上传文件的脚本

php中文网

php中文网

发布时间:2016-06-23 13:33:16

|

895人浏览过

|

来源于php中文网

原创

为什么使用这个类?

因为碰到一个蛋疼的项目,项目服务器在另外一家公司(简称公司甲)手上,公司甲,他们服务器不开放外网权限,怕出问题。因为项目正在开发中, 所以经常需要上传php代码到服务器去,由于没权限,所以上传代码采用了效率超级慢的人工上传-_-,在我再三要求下,最后给开了一个跳板机的ftp,每次上传代码到这个ftp,然后公司甲,自动的将ftp里面的代码同步到对应的服务器。

然后,问题又来了,ftp只对指定ip的客户开放,然后工作地点的公网ip又是经常变化,所以无奈之下,将这个ip指向了一台测试用的linux 操作系统的服务器.

然后,问题又继续来了,由于服务器没有gui界面,ftp只支持命令行,执行多次上传操作,那个过程,谁用谁知道,所以在此无奈之下,产生了下面这个类, 用php 来控制一键上传.

简灰服装商城整站 For SHOPEX
简灰服装商城整站 For SHOPEX

SHOPEX简灰服装商城整站源码下载。 安装方法:1.解压上传程序至网站根目录.. 访问:域名/bak.(用户名:admin 密码:123456)2.进入帝国备份王后,配置数据库数据库信息.选择-www.taomoban.net目录.还原数据库.3.修改FTP目录下的config/config.phpphp 数据库连接信息.4.登陆网站后台--清空缓存..5.删除bak文件夹 后台:shopadm

下载

大概原理

  • 遍历项目中的所有非排除文件,然后获取文件修改时间晚于文件上一次修改时间的文件
  • 然后将这些文件,通过ftp上传到对应的目录
  • 具体代码如下:

    因为只是工具,代码很乱,见谅

    phpZip($path); //过滤出最新的修改文件$path = str_replace("/data/longtu/","",$path);$config = array(        'hostname' => 'xxx.xxx.xx.xxx', //ftp服务器 地址        'username' => 'xxx',            //ftp用户        'password' => '?xxxxxxxxxxx', //ftp密码        'port' => 21                    //端口);$ftp = new Ftp();$ftp->connect($config);                //链接服务器//$a=$ftp->filelist();$LOCAL_ROOT = realpath(dirname(__DIR__)."/../../");chdir($LOCAL_ROOT);foreach ($files as $k=>$v){      $f = $path.$v;      $tmp = $ftp->upload($f, $f);      if($tmp){        echo "upload $f -> success \n";      }}//$ftp->download('ftp_upload.log','ftp_download.log');////$ftp->upload('ftp_err.log','ftp_upload.log');//$ftp->download('ftp_upload.log','ftp_download.log');/* * * *  $dir = "/test";    if(@ftp_chdir($conn, $dir))     判断是否为文件夹 * Enter description here ... * @author Administrator * */class FilerFile{    var $time_path;    private $fctimes = array();    function Zip($dir)    {        $this->time_path = rtrim($dir,"/")."/.~~~time.php";        //@unlink($this->time_path);        $filelist = $this -> GetFileList($dir);        file_put_contents($this->time_path,"fctimes,true).";");        return $filelist;    }    function appendFilectime($file)    {        $time_file_path = $this->time_path;        $ftime = @include($time_file_path);        $ftime = $ftime ? $ftime : array();        $time = filectime($file);        if(!file_exists($time_file_path))file_put_contents($time_file_path,"time_path;        if (!$time_data){            $time_data= @include_once($time_file_path);        }        $time_data = $time_data ? $time_data : array();        //var_dump($file,$time_data[$file] == filectime($file));        //echo $file."\t".$time_data[$file]."\n";        if ($time_data[$file] == filemtime($file)){            return false;        }else{            return $file;        }    }    function GetFileList($dir,$path="")    {        static $tmpp = "";        if ($path=="" && !$tmpp){            $tmpp = $dir;        }        $d = dir($dir);        $files = array();        if ($d)        {            $pathP=str_replace($tmpp,"",$dir);            $pathP=str_replace(array("\\\\","/"),DIRECTORY_SEPARATOR,$pathP);            $pathP=str_replace(DIRECTORY_SEPARATOR.DIRECTORY_SEPARATOR,DIRECTORY_SEPARATOR,$pathP);            while($f = $d->read())            {                if ($f == '.' || $f=='..' || $f{0}=='.' || $f=='Zend' || in_array($f, $_GET['exclude']))continue;                $newdir = rtrim($dir,"/")."/".$f;                if (is_dir($newdir)){                    $files = array_merge($files,$this->GetFileList($newdir,$newdir));                }else{                    $abspath_file = (rtrim($dir,"/") ? rtrim($dir,"/")."/" : "").$f;                    $this->fctimes[$abspath_file] = filemtime($abspath_file);                    if (!$this->getFileByFilectime($abspath_file))continue;                    $file = (rtrim($pathP,"/") ? rtrim($pathP,"/")."/" : "").$f;                    $files[] = $file;                }            }        }        return $files;    }}/** * 仿写CodeIgniter的FTP类 * FTP基本操作: * 1) 登陆;           connect * 2) 当前目录文件列表;  filelist * 3) 目录改变;         chgdir * 4) 重命名/移动;       rename * 5) 创建文件夹;        mkdir * 6) 删除;               delete_dir/delete_file * 7) 上传;               upload * 8) 下载                download * * @author quanshuidingdang */class Ftp {    private $hostname   = '';    private $username   = '';    private $password   = '';    private $port       = 21;    private $passive    = TRUE;    private $debug      = TRUE;    private $conn_id    = FALSE;    /**     * 构造函数     *     * @param   array   配置数组 : $config = array('hostname'=>'','username'=>'','password'=>'','port'=>''...);     */    public function __construct($config = array()) {        if(count($config) > 0) {            $this->_init($config);        }    }    /**     * FTP连接     *     * @access  public     * @param   array   配置数组     * @return  boolean     */    public function connect($config = array()) {        if(count($config) > 0) {            $this->_init($config);        }        if(FALSE === ($this->conn_id = @ftp_connect($this->hostname,$this->port))) {            if($this->debug === TRUE) {                $this->_error("ftp_unable_to_connect");            }            return FALSE;        }        if( ! $this->_login()) {            if($this->debug === TRUE) {                $this->_error("ftp_unable_to_login");            }            return FALSE;        }        if($this->passive === TRUE) {            ftp_pasv($this->conn_id, TRUE);        }        return TRUE;    }    /**     * 文件夹是否存在     * @param unknown_type $path     */    public function is_dir_exists($path)    {        return $this->chgdir($path);    }    /**     * 目录改变     *     * @access  public     * @param   string  目录标识(ftp)     * @param   boolean      * @return  boolean     */    public function chgdir($path = '', $supress_debug = FALSE) {        if($path == '' OR ! $this->_isconn()) {            return FALSE;        }        $result = @ftp_chdir($this->conn_id, $path);        if($result === FALSE) {            if($this->debug === TRUE AND $supress_debug == FALSE) {                $this->_error("ftp_unable_to_chgdir:dir[".$path."]");            }            return FALSE;        }        return TRUE;    }    /**     * 目录生成     *     * @access  public     * @param   string  目录标识(ftp)     * @param   int     文件权限列表       * @return  boolean     */    public function mkdir($path = '', $permissions = NULL) {        if($path == '' OR ! $this->_isconn()) {            return FALSE;        }        $result = @ftp_mkdir($this->conn_id, $path);        if($result === FALSE) {            if($this->debug === TRUE) {                $this->_error("ftp_unable_to_mkdir:dir[".$path."]");            }            return FALSE;        }        if( ! is_null($permissions)) {            $this->chmod($path,(int)$permissions);        }        return TRUE;    }    /**     * 上传     *     * @access  public     * @param   string  本地目录标识     * @param   string  远程目录标识(ftp)     * @param   string  上传模式 auto || ascii     * @param   int     上传后的文件权限列表       * @return  boolean     */    public function upload($localpath, $remotepath, $mode = 'auto', $permissions = NULL) {        if( ! $this->_isconn()) {            return FALSE;        }        if( ! file_exists($localpath)) {            if($this->debug === TRUE) {                $this->_error("ftp_no_source_file:".$localpath);            }            return FALSE;        }        if($mode == 'auto') {            $ext = $this->_getext($localpath);            $mode = $this->_settype($ext);        }        $mode = ($mode == 'ascii') ? FTP_ASCII : FTP_BINARY;        $result = @ftp_put($this->conn_id, $remotepath, $localpath, $mode);        if($result === FALSE) {            if($this->debug === TRUE) {                $this->_error("ftp_unable_to_upload:localpath[".$localpath."]/remotepath[".$remotepath."]");            }            return FALSE;        }        if( ! is_null($permissions)) {            $this->chmod($remotepath,(int)$permissions);        }        return TRUE;    }    /**     * 下载     *     * @access  public     * @param   string  远程目录标识(ftp)     * @param   string  本地目录标识     * @param   string  下载模式 auto || ascii       * @return  boolean     */    public function download($remotepath, $localpath, $mode = 'auto') {        if( ! $this->_isconn()) {            return FALSE;        }        if($mode == 'auto') {            $ext = $this->_getext($remotepath);            $mode = $this->_settype($ext);        }        $mode = ($mode == 'ascii') ? FTP_ASCII : FTP_BINARY;        $result = @ftp_get($this->conn_id, $localpath, $remotepath, $mode);        if($result === FALSE) {            if($this->debug === TRUE) {                $this->_error("ftp_unable_to_download:localpath[".$localpath."]-remotepath[".$remotepath."]");            }            return FALSE;        }        return TRUE;    }    /**     * 重命名/移动     *     * @access  public     * @param   string  远程目录标识(ftp)     * @param   string  新目录标识     * @param   boolean 判断是重命名(FALSE)还是移动(TRUE)      * @return  boolean     */    public function rename($oldname, $newname, $move = FALSE) {        if( ! $this->_isconn()) {            return FALSE;        }        $result = @ftp_rename($this->conn_id, $oldname, $newname);        if($result === FALSE) {            if($this->debug === TRUE) {                $msg = ($move == FALSE) ? "ftp_unable_to_rename" : "ftp_unable_to_move";                $this->_error($msg);            }            return FALSE;        }        return TRUE;    }    /**     * 删除文件     *     * @access  public     * @param   string  文件标识(ftp)     * @return  boolean     */    public function delete_file($file) {        if( ! $this->_isconn()) {            return FALSE;        }        $result = @ftp_delete($this->conn_id, $file);        if($result === FALSE) {            if($this->debug === TRUE) {                $this->_error("ftp_unable_to_delete_file:file[".$file."]");            }            return FALSE;        }        return TRUE;    }    /**     * 删除文件夹     *     * @access  public     * @param   string  目录标识(ftp)     * @return  boolean     */    public function delete_dir($path) {        if( ! $this->_isconn()) {            return FALSE;        }        //对目录宏的'/'字符添加反斜杠'\'        $path = preg_replace("/(.+?)\/*$/", "\\1/", $path);        //获取目录文件列表        $filelist = $this->filelist($path);        if($filelist !== FALSE AND count($filelist) > 0) {            foreach($filelist as $item) {                //如果我们无法删除,那么就可能是一个文件夹                //所以我们递归调用delete_dir()                if( ! @delete_file($item)) {                    $this->delete_dir($item);                }            }        }        //删除文件夹(空文件夹)        $result = @ftp_rmdir($this->conn_id, $path);        if($result === FALSE) {            if($this->debug === TRUE) {                $this->_error("ftp_unable_to_delete_dir:dir[".$path."]");            }            return FALSE;        }        return TRUE;    }    /**     * 修改文件权限     *     * @access  public     * @param   string  目录标识(ftp)     * @return  boolean     */    public function chmod($path, $perm) {        if( ! $this->_isconn()) {            return FALSE;        }        //只有在PHP5中才定义了修改权限的函数(ftp)        if( ! function_exists('ftp_chmod')) {            if($this->debug === TRUE) {                $this->_error("ftp_unable_to_chmod(function)");            }            return FALSE;        }        $result = @ftp_chmod($this->conn_id, $perm, $path);        if($result === FALSE) {            if($this->debug === TRUE) {                $this->_error("ftp_unable_to_chmod:path[".$path."]-chmod[".$perm."]");            }            return FALSE;        }        return TRUE;    }    /**     * 获取目录文件列表     *     * @access  public     * @param   string  目录标识(ftp)     * @return  array     */    public function filelist($path = '.') {        if( ! $this->_isconn()) {            return FALSE;        }        return ftp_nlist($this->conn_id, $path);    }    /**     * 关闭FTP     *     * @access  public     * @return  boolean     */    public function close() {        if( ! $this->_isconn()) {            return FALSE;        }        return @ftp_close($this->conn_id);    }    /**     * FTP成员变量初始化     *     * @access  private     * @param   array   配置数组          * @return  void     */    private function _init($config = array()) {        foreach($config as $key => $val) {            if(isset($this->$key)) {                $this->$key = $val;            }        }        //特殊字符过滤        $this->hostname = preg_replace('|.+?://|','',$this->hostname);    }    /**     * FTP登陆     *     * @access  private     * @return  boolean     */    private function _login() {        return @ftp_login($this->conn_id, $this->username, $this->password);    }    /**     * 判断con_id     *     * @access  private     * @return  boolean     */    private function _isconn() {        if( ! is_resource($this->conn_id)) {            if($this->debug === TRUE) {                $this->_error("ftp_no_connection");            }            return FALSE;        }        return TRUE;    }    /**     * 从文件名中获取后缀扩展     *     * @access  private     * @param   string  目录标识     * @return  string     */    private function _getext($filename) {        if(FALSE === strpos($filename, '.')) {            return 'txt';        }        $extarr = explode('.', $filename);        return end($extarr);    }    /**     * 从后缀扩展定义FTP传输模式  ascii 或 binary     *     * @access  private     * @param   string  后缀扩展     * @return  string     */    private function _settype($ext) {        $text_type = array (                            'txt',                            'text',                            'php',                            'phps',                            'php4',                            'js',                            'css',                            'htm',                            'html',                            'phtml',                            'shtml',                            'log',                            'xml'                            );        return (in_array($ext, $text_type)) ? 'ascii' : 'binary';    }    /**     * 错误日志记录     *     * @access  prvate     * @return  boolean     */    private function _error($msg) {        return @file_put_contents('/tmp/ftp_err.log', "date[".date("Y-m-d H:i:s")."]-hostname[".$this->hostname."]-username[".$this->username."]-password[".$this->password."]-msg[".$msg."]\n", FILE_APPEND);    }}/*End of file ftp.php*//*Location /Apache Group/htdocs/ftp.php*/

    相关文章

    PHP速学教程(入门到精通)
    PHP速学教程(入门到精通)

    PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!

    下载

    本站声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn

    热门AI工具

    更多
    DeepSeek
    DeepSeek

    幻方量化公司旗下的开源大模型平台

    豆包大模型
    豆包大模型

    字节跳动自主研发的一系列大型语言模型

    通义千问
    通义千问

    阿里巴巴推出的全能AI助手

    腾讯元宝
    腾讯元宝

    腾讯混元平台推出的AI助手

    文心一言
    文心一言

    文心一言是百度开发的AI聊天机器人,通过对话可以生成各种形式的内容。

    讯飞写作
    讯飞写作

    基于讯飞星火大模型的AI写作工具,可以快速生成新闻稿件、品宣文案、工作总结、心得体会等各种文文稿

    即梦AI
    即梦AI

    一站式AI创作平台,免费AI图片和视频生成。

    ChatGPT
    ChatGPT

    最最强大的AI聊天机器人程序,ChatGPT不单是聊天机器人,还能进行撰写邮件、视频脚本、文案、翻译、代码等任务。

    相关专题

    更多
    Golang处理数据库错误教程合集
    Golang处理数据库错误教程合集

    本专题整合了Golang数据库错误处理方法、技巧、管理策略相关内容,阅读专题下面的文章了解更多详细内容。

    39

    2026.02.06

    java多线程方法汇总
    java多线程方法汇总

    本专题整合了java多线程面试题、实现函数、执行并发相关内容,阅读专题下面的文章了解更多详细内容。

    17

    2026.02.06

    1688阿里巴巴货源平台入口与批发采购指南
    1688阿里巴巴货源平台入口与批发采购指南

    本专题整理了1688阿里巴巴批发进货平台的最新入口地址与在线采购指南,帮助用户快速找到官方网站入口,了解如何进行批发采购、货源选择以及厂家直销等功能,提升采购效率与平台使用体验。

    289

    2026.02.06

    快手网页版入口与电脑端使用指南 快手官方短视频观看入口
    快手网页版入口与电脑端使用指南 快手官方短视频观看入口

    本专题汇总了快手网页版的最新入口地址和电脑版使用方法,详细提供快手官网直接访问链接、网页端操作教程,以及如何无需下载安装直接观看短视频的方式,帮助用户轻松浏览和观看快手短视频内容。

    150

    2026.02.06

    C# 多线程与异步编程
    C# 多线程与异步编程

    本专题深入讲解 C# 中多线程与异步编程的核心概念与实战技巧,包括线程池管理、Task 类的使用、async/await 异步编程模式、并发控制与线程同步、死锁与竞态条件的解决方案。通过实际项目,帮助开发者掌握 如何在 C# 中构建高并发、低延迟的异步系统,提升应用性能和响应速度。

    11

    2026.02.06

    Python 微服务架构与 FastAPI 框架
    Python 微服务架构与 FastAPI 框架

    本专题系统讲解 Python 微服务架构设计与 FastAPI 框架应用,涵盖 FastAPI 的快速开发、路由与依赖注入、数据模型验证、API 文档自动生成、OAuth2 与 JWT 身份验证、异步支持、部署与扩展等。通过实际案例,帮助学习者掌握 使用 FastAPI 构建高效、可扩展的微服务应用,提高服务响应速度与系统可维护性。

    7

    2026.02.06

    JavaScript 异步编程与事件驱动架构
    JavaScript 异步编程与事件驱动架构

    本专题深入讲解 JavaScript 异步编程与事件驱动架构,涵盖 Promise、async/await、事件循环机制、回调函数、任务队列与微任务队列、以及如何设计高效的异步应用架构。通过多个实际示例,帮助开发者掌握 如何处理复杂异步操作,并利用事件驱动设计模式构建高效、响应式应用。

    11

    2026.02.06

    java连接字符串方法汇总
    java连接字符串方法汇总

    本专题整合了java连接字符串教程合集,阅读专题下面的文章了解更多详细操作。

    47

    2026.02.05

    java中fail含义
    java中fail含义

    本专题整合了java中fail的含义、作用相关内容,阅读专题下面的文章了解更多详细内容。

    29

    2026.02.05

    热门下载

    更多
    网站特效
    /
    网站源码
    /
    网站素材
    /
    前端模板

    精品课程

    更多
    相关推荐
    /
    热门推荐
    /
    最新课程
    PHP基础入门课程
    PHP基础入门课程

    共33课时 | 2.1万人学习

    PHP开发简单文件上传教程
    PHP开发简单文件上传教程

    共9课时 | 6万人学习

    关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
    php中文网:公益在线php培训,帮助PHP学习者快速成长!
    关注服务号 技术交流群
    PHP中文网订阅号
    每天精选资源文章推送

    Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号