您的位置:新葡亰496net > 新葡亰官网 > 新葡亰496net多图片上传程序代码,一个实用的p

新葡亰496net多图片上传程序代码,一个实用的p

发布时间:2019-06-18 08:32编辑:新葡亰官网浏览(158)

    静态能源文件自动削减并替换来压缩版本(大型网址优化本事)

    2015/11/26 · HTML5 · 静态能源

    原版的书文出处: Kelly   

    那二遍,小编计算和享受一项大型网站优化技能,那正是在项目中活动削减静态能源文件(css、js),并让网址自动加载压缩后的财富文件。当然,那项技能在雅虎35条前端优化提议里也是有记载,但它那只是给出叁个理论的方案而已,并且使用的是表面压缩工具去收缩,而在自家的连串中,是一贯通过友好的程序自动化去减弱全数css、js文件,然后让页面从来加载所裁减后的财富,接下去直接进入正题。

    此番实验应用的是PHP脚本语言,版本是PHP5.6,是在LINUX下搭建的情状(网络搭建无论是搭建LAMP依然LNMP的教程都有滋有味一塌糊涂,后一次作者会总括和享受什么在LINUX下搭建服务器情形的博文,而且搭建的条件必须一遍性搭建成功的)。所选拔的框架是CI框架,所采纳的模板是斯Matty模板引擎。当然了,这么些只是本人所利用的情况而已,如若您是PHP开拓者,假设你要测试下此次试验,那么,作者提议你的PHP版本选拔5.4之上,至于框架用什么样都以足以的。而只要你不是PHP开垦者(你是JSP或许是ASP开采者恐怕是别的开采者),那么您知道好这一思路后,完全能够在友好深谙的言语里张开尝试测试。

    一、原理图

    率先小编画一张思路图,便于大家先清楚。

    首先是能源减弱原理图:

    新葡亰496net 1

    继而是财富文件替换的原理图:

    新葡亰496net 2

    新葡亰496net多图片上传程序代码,一个实用的php。借使大家认真领会并且看懂这两张原理图的话,基本上也就调控了自身所享受的笔触。纵然仍旧不能够领略的话,接下去小编会结合代码,对以上原理图的每一步进行详尽讲授。

    二、思路详细分析

    1.先是是调用该滑坡的方法,你能够把该方法放在网址所要加载的公共类的地点,举个例子每便访问网址都会调用该滑坡方法实行压缩。当然,这几个只是在付出条件才会每一遍都调用,若是是线上的情形,在你的网址发二遍新本子的时候,调用一遍用来生成压缩版的静态能源就可以了。

    class MY_Controller extends CI_Controller { public function __construct() { parent::__construct(); //压缩jscss财富文件 $this->compressResHandle(); } /** * 压缩js、css资源文件(优化) * @return [type] [description] */ private function compressResHandle() { $this->load->library('ResMinifier'); //压缩钦定文件夹下的能源文件 $this->resminifier->compressRes(); } }

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    class MY_Controller extends CI_Controller {
        public function __construct() {
            parent::__construct();
     
            //压缩jscss资源文件
            $this->compressResHandle();
        }
        /**
         * 压缩js、css资源文件(优化)
         * @return [type] [description]
         */
        private function compressResHandle() {
            $this->load->library('ResMinifier');
            //压缩指定文件夹下的资源文件
            $this->resminifier->compressRes();
        }
    }

    2.随后就调用了 ResMinifier类里的 compressRes方法。在此处自个儿先附上 ResMinifier那几个类的代码,然后方便一步步进行解析解说

    PHP

    <?php defined('BASEPATH') OR exit('No direct script access allowed'); /** * 财富压缩类 */ class ResMinifier { /** 要求减小的财富目录*/ public $compressResDir = ['css', 'js']; /** 忽略压缩的门路,譬喻此处是js/icon早先的不二等秘书诀忽略压缩*/ public $compressResIngorePrefix = ['js/icon']; /** 能源根目录*/ public $resRootDir; /** 财富版本文件路线*/ private $resStatePath; public function __construct() { $this->resRootDir = WEBROOT . 'www/'; $this->resStatePath = WEBROOT . 'www/resState.php'; } public function compressRes() { //获取存放版本的财富文件 $resState = $this->getResState(); $count = 0; //开头遍历需求减弱的财富目录 foreach ($this->compressResDir as $resDir) { foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator($this->resRootDir . $resDir , FilesystemIterator::SKIP_DOTS)) as $file) { //获取该财富文件的相对路径$filePath = str_replace('\', '/', $file->getRealPath()); //获取文件相对路线 $object = substr($filePath, strlen($this->resRootDir)); //总计文件的版本号 $state = $this->_getResStateVersion($filePath); //获取文件的多少个参数值 if (true !== $this->getObjectInfo($object, $minObject, $needCompress, $state, $extension)) { continue; } //压缩文件的相对路线 $minFilePath = str_replace('\', '/', $this->resRootDir. $minObject); //************此处p判定是最主要片段之一*****************// //判别文件是不是留存且早已改成过 if (isset($resState[$object]) && $resState[$object] == $state && isset($resState[$minObject]) && file_exists($minFilePath)) { continue; } //确定保证/www/min/目录可写 $this->_ensureWritableDir(dirname($minFilePath)); if ($needCompress) { $this->compressResFileAndSave($filePath, $minFilePath); } else { copy($filePath, $minFilePath); } $resState[$object] = $state; $resState[$minObject] = ''; $count ; if ($count == 50) { $this->_saveResState($resState); $count = 0; } } } if($count) $this->_saveResState($resState); } public function getObjectInfo($object, &$minObject, &$needCompress, &$state, &$extension) { //获取财富相对路径 $file帕特h = $this->resRootDir . $object; //判定能源是或不是留存 if (!file_exists($filePath)) return "能源文件不设有{$file帕特h}"; //版本号 $state = $this-> _getResStateVersion($filePath); //文件名后缀 $extension = pathinfo($filePath, PATHINFO_EXTENSION); //是还是不是要缩短 $needCompress = true; //判定财富文件是或不是是以 .min.css也许.min.js结尾的 //此类结尾一般都以已压缩过,举个例子jquery.min.js,就不用再压缩了 if (str_end_with($object, '.min.'.$extension, true)) { //压缩后的能源存放路线,放在 /www/min/ 目录下 $minObject = 'min/'.substr($object, 0, strlen($object) - strlen($extension) - 4) . $state .'.'. $extension; $needCompress = false; } else if (in_array($extension, $this->compressResDir)) { //此处是内需减小的文件目录 $minObject = 'min/'.substr($object, 0, strlen($object) - strlen($extension)) . $state . '.' . $extension; //看看是不是是忽略的门路前缀 foreach ($this->compressResIngorePrefix as $v) { if (str_start_with($object, $v, true)) { $needCompress = false; } } } else { $minObject = 'min/'.$object; $needCompress = false; } return true; } /** * 获取存放能源版本的文件 * 它是献身叁个数组里 * $resState = array( * '文件路线' => '对应的本子号', * '文件路线' => '对应的版本号', * '文件路线' => '对应的版本号', * ); * @return [type] [description] */ public function getResState() { if (file_exists($this->resStatePath)) { require $this->resStatePath; return $resState; } return []; } /** * 总结文件的本子号,那一个是基于测算文件MD5散列值获得版本号 * 只要文件内容改变了,所计算获得的散列值就能够不平等 * 用于判别能源文件是还是不是有退换过 * @param [type] $filePath [description] * @return [type] [description] */ public function _getResStateVersion($filePath) { return base_convert(crc32(md5_file($filePath)), 10, 36); } /** * 确定保证目录可写 * @param [type] $dir [description] * @return [type] [description] */ private function _ensureWritableDir($dir) { if (!file_exists($dir)) { @mkdir($dir, 0777, true); @chmod($dir, 0777); } else if (!is_writable($dir)) { @chmod($dir, 0777); if (!is_writable($dir)) { show_error('目录'.$dir.'不可写'); } } } /** * 将缩减后的能源文件写入到/www/min/下去 * @param [type] $filePath [description] * @param [type] $minFilePath [description] * @return [type] [description] */ private function compressResFileAndSave($filePath, $minFilePath) { if (!file_put_contents($minFilePath, $this->compressResFile($filePath))) { //$CI->exceptions->show_exception("写入文件{$minFilePath}失利"); show_error("写入文件{$minFilePath}失利", -1); } } /** * 压缩财富文件 * @param [type] $filePath [description] * @return [type] [description] */ private function compressResFile($filePath) { $extension = strtolower(pathinfo($filePath, PATHINFO_EXTENSION)); if ($extension === 'js') { require_once 'JShrink/Minifier.php'; return JShrinkMinifier::minify(file_get_contents($filePath)); } else if ($extension ==='css') { $content = file_get_contents($filePath); $content = preg_replace('!/*[^*]** ([^/][^*]** )*/!', '', $content); $content = str_replace(["rn", "r", "n"], '', $content); $content = preg_replace('/([{}),;:>])s /', '$1', $content); $content = preg_replace('/s ([{}),;:>])/', '$1', $content); $content = str_replace(';}', '}', $content); return $content; } else { //$CI->exceptions->show_exception("不支持压缩{extension}文件[$filePath]"); show_error("不帮助压缩{extension}文件[$filePath]", -1); } } private function _saveResState($resState) { ksort($resState); $content = "<?phpnn$resState = array(n"; foreach ($resState as $k => $v) { $content .= "t '$k' => '$v',n"; } $content .= ");nn"; file_put_contents($this->resStatePath, $content); } } 点击展开财富压缩类

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    <?php
    defined('BASEPATH') OR exit('No direct script access allowed');
    /**
    * 资源压缩类
    */
    class ResMinifier {
        /** 需要压缩的资源目录*/
        public $compressResDir = ['css', 'js'];
        /** 忽略压缩的路径,例如此处是js/icon开头的路径忽略压缩*/
        public $compressResIngorePrefix = ['js/icon'];
        /** 资源根目录*/
        public $resRootDir;
        /** 资源版本文件路径*/
        private $resStatePath;
     
        public function __construct() {
            $this->resRootDir = WEBROOT . 'www/';
            $this->resStatePath = WEBROOT . 'www/resState.php';
        }
     
        public function compressRes() {
            //获取存放版本的资源文件
            $resState = $this->getResState();
            $count = 0;
     
            //开始遍历需要压缩的资源目录
            foreach ($this->compressResDir as $resDir) {
                foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator($this->resRootDir . $resDir , FilesystemIterator::SKIP_DOTS)) as $file) {
                    //获取该资源文件的绝对路径
                    $filePath = str_replace('\', '/', $file->getRealPath());
                    //获取文件相对路径
                    $object = substr($filePath, strlen($this->resRootDir));
                    //计算文件的版本号
                    $state = $this->_getResStateVersion($filePath);
     
                    //获取文件的几个参数值
                    if (true !== $this->getObjectInfo($object, $minObject, $needCompress, $state, $extension)) {
                        continue;
                    }
     
                    //压缩文件的绝对路径
                    $minFilePath = str_replace('\', '/', $this->resRootDir. $minObject);
     
                    //************此处p判断是最重要部分之一*****************//
                    //判断文件是否存在且已经改动过
                    if (isset($resState[$object]) && $resState[$object] == $state && isset($resState[$minObject]) && file_exists($minFilePath)) {
                        continue;
                    }
     
                    //确保/www/min/目录可写
                    $this->_ensureWritableDir(dirname($minFilePath));
     
                    if ($needCompress) {
                        $this->compressResFileAndSave($filePath, $minFilePath);
                    } else {
                        copy($filePath, $minFilePath);
                    }
     
                    $resState[$object] = $state;
                    $resState[$minObject] = '';
                    $count ;
     
                    if ($count == 50) {
                        $this->_saveResState($resState);
                        $count = 0;
                    }
     
                }
            }
            if($count) $this->_saveResState($resState);
        }
     
        public function getObjectInfo($object, &$minObject, &$needCompress, &$state, &$extension) {
            //获取资源绝对路径
            $filePath = $this->resRootDir . $object;
            //判断资源是否存在
            if (!file_exists($filePath)) return "资源文件不存在{$filePath}";
            //版本号
            $state = $this-> _getResStateVersion($filePath);
            //文件名后缀
            $extension = pathinfo($filePath, PATHINFO_EXTENSION);
            //是否要压缩
            $needCompress = true;
     
            //判断资源文件是否是以 .min.css或者.min.js结尾的
            //此类结尾一般都是已压缩过,例如jquery.min.js,就不必再压缩了
            if (str_end_with($object, '.min.'.$extension, true)) {
                //压缩后的资源存放路径,放在 /www/min/ 目录下
                $minObject = 'min/'.substr($object, 0, strlen($object) - strlen($extension) - 4) . $state .'.'. $extension;
                $needCompress = false;
            } else if (in_array($extension, $this->compressResDir)) {
                //此处是需要压缩的文件目录
                $minObject = 'min/'.substr($object, 0, strlen($object) - strlen($extension)) . $state . '.' . $extension;
                //看看是否是忽略的路径前缀
                foreach ($this->compressResIngorePrefix as $v) {
                    if (str_start_with($object, $v, true)) {
                        $needCompress = false;
                    }
                }
            } else {
                $minObject = 'min/'.$object;
                $needCompress = false;
            }
            return true;
        }
     
        /**
         * 获取存放资源版本的文件
         * 它是放在一个数组里
         * $resState = array(
         *         '文件路径' => '对应的版本号',
         *         '文件路径' => '对应的版本号',
         *         '文件路径' => '对应的版本号',
         *     );
         * @return [type] [description]
         */
        public function getResState() {
            if (file_exists($this->resStatePath)) {
                require $this->resStatePath;
                return $resState;
            }
            return [];
        }
     
        /**
         * 计算文件的版本号,这个是根据计算文件MD5散列值得到版本号
         * 只要文件内容改变了,所计算得到的散列值就会不一样
         * 用于判断资源文件是否有改动过
         * @param  [type] $filePath [description]
         * @return [type]           [description]
         */
        public function _getResStateVersion($filePath) {
            return base_convert(crc32(md5_file($filePath)), 10, 36);
        }
     
        /**
         * 确保目录可写
         * @param  [type] $dir [description]
         * @return [type]      [description]
         */
        private function _ensureWritableDir($dir) {
            if (!file_exists($dir)) {
                @mkdir($dir, 0777, true);
                @chmod($dir, 0777);
            } else if (!is_writable($dir)) {
                @chmod($dir, 0777);
                if (!is_writable($dir)) {
                    show_error('目录'.$dir.'不可写');
                }
            }
        }
     
        /**
         * 将压缩后的资源文件写入到/www/min/下去
         * @param  [type] $filePath    [description]
         * @param  [type] $minFilePath [description]
         * @return [type]              [description]
         */
        private function compressResFileAndSave($filePath, $minFilePath) {
            if (!file_put_contents($minFilePath, $this->compressResFile($filePath))) {
     
                //$CI->exceptions->show_exception("写入文件{$minFilePath}失败");
                show_error("写入文件{$minFilePath}失败", -1);
            }
        }
     
        /**
         * 压缩资源文件
         * @param  [type] $filePath [description]
         * @return [type]           [description]
         */
        private function compressResFile($filePath) {
            $extension = strtolower(pathinfo($filePath, PATHINFO_EXTENSION));
            if ($extension === 'js') {
                require_once 'JShrink/Minifier.php';
                return JShrinkMinifier::minify(file_get_contents($filePath));
            } else if ($extension ==='css') {
                $content = file_get_contents($filePath);
                $content = preg_replace('!/*[^*]** ([^/][^*]** )*/!', '', $content);
                $content = str_replace(["rn", "r", "n"], '', $content);
                $content = preg_replace('/([{}),;:>])s /', '$1', $content);
                $content = preg_replace('/s ([{}),;:>])/', '$1', $content);
                $content = str_replace(';}', '}', $content);
                return $content;
            } else {
                //$CI->exceptions->show_exception("不支持压缩{extension}文件[$filePath]");
                show_error("不支持压缩{extension}文件[$filePath]", -1);
     
            }
        }
     
        private function _saveResState($resState) {
            ksort($resState);
            $content = "<?phpnn$resState = array(n";
            foreach ($resState as $k => $v) {
                $content .= "t '$k' => '$v',n";
            }
            $content .= ");nn";
            file_put_contents($this->resStatePath, $content);
        }
     
    }
     
    点击打开 资源压缩类

    整个类大部分代码作者都加了解说,方便我们飞速掌握。这里自身也会对每一行代码进行表明。

    (1)

    PHP

    /** 须要减小的能源目录*/ public $compressResDir = ['css', 'js']; /** 忽略压缩的不二秘诀,举个例子此处是js/icon起始的路子忽略压缩*/ public $compressResIngorePrefix = ['js/icon']; /** 能源根目录*/ public $resRootDir; /** 财富版本文件路径*/ private $resStatePath; public function __construct() { $this->resRootDir = WEBROOT . 'www/'; $this->resStatePath = WEBROOT . 'www/resState.php'; }

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    /** 需要压缩的资源目录*/
        public $compressResDir = ['css', 'js'];
        /** 忽略压缩的路径,例如此处是js/icon开头的路径忽略压缩*/
        public $compressResIngorePrefix = ['js/icon'];
        /** 资源根目录*/
        public $resRootDir;
        /** 资源版本文件路径*/
        private $resStatePath;
     
        public function __construct() {
            $this->resRootDir = WEBROOT . 'www/';
            $this->resStatePath = WEBROOT . 'www/resState.php';
        }

    $compressResDir变量是内需减小的财富目录,假设你有新的拍卖目录,能够在此变量里假诺新的目录名就能够处理。附上本身测试项指标目录图

    新葡亰496net 3

    $compressResIngorePrefix 忽略被削减的路径的路径前有的是该数组变量的字符串,比如有三个能源路线为 js/icon/bg.js可能是js/icon_index.js或许是js/icon.header.js,若是在该数组中投入了 js/icon这些字符串,那么能源路线为js/icon开始的都会被忽略掉,也正是一向跳过,不用压缩。(因为能源文件里总有一些是无需减小的嘛)

    $resRootDir存放财富根目录的

    $resStatePath 那么些是能源版本文件路径

    (2)进入compressRes() 方法,大家先深入分析前边这一段代码

    PHP

    public function compressRes() { //获取存放版本的财富文件 $resState = $this->getResState(); $count = 0;

    1
    2
    3
    4
    public function compressRes() {
            //获取存放版本的资源文件
            $resState = $this->getResState();
            $count = 0;

    ——————————-调用getResState() 讲解start————————————————————-

    此地首先是调用 $this->getResState() 方法来获取存放版本的财富文件,此处先跳到该措施看看是怎么着写的,其实正是富含该文件,然后回来里面存放版本号的数组,大家看注释可以明白该公文里存放版本号的格式(顺便附上图让大家看看)

    PHP

    /** * 获取存放财富版本的文本 * 它是身处一个数组里 * $resState = array( * '文件路线' => '对应的本子号', * '文件路线' => '对应的本子号', * '文件路线' => '对应的版本号', * ); * @return [type] [description] */ public function getResState() { if (file_exists($this->resStatePath)) { require $this->resStatePath; return $resState; } return []; }

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    /**
         * 获取存放资源版本的文件
         * 它是放在一个数组里
         * $resState = array(
         *         '文件路径' => '对应的版本号',
         *         '文件路径' => '对应的版本号',
         *         '文件路径' => '对应的版本号',
         *     );
         * @return [type] [description]
         */
        public function getResState() {
            if (file_exists($this->resStatePath)) {
                require $this->resStatePath;
                return $resState;
            }
            return [];
        }

    (能源版本文件截图:)

    新葡亰496net 4

    ——————————-调用getResState() 讲解end————————————————————-

    紧接着看compressRes()里的这一段代码

    PHP

    //开始遍历须求收缩的财富目录 foreach ($this->compressResDir as $resDir) { foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator($this->resRootDir . $resDir , FilesystemIterator::SKIP_DOTS)) as $file) { //获取该能源文件的相对路线$filePath = str_replace('\', '/', $file->getRealPath()); //获取文件相对路线 $object = substr($filePath, strlen($this->resRootDir)); //总结文件的本子号 $state = $this->_getResStateVersion($filePath);

    1
    2
    3
    4
    5
    6
    7
    8
    9
    //开始遍历需要压缩的资源目录
            foreach ($this->compressResDir as $resDir) {
                foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator($this->resRootDir . $resDir , FilesystemIterator::SKIP_DOTS)) as $file) {
                    //获取该资源文件的绝对路径
                    $filePath = str_replace('\', '/', $file->getRealPath());
                    //获取文件相对路径
                    $object = substr($filePath, strlen($this->resRootDir));
                    //计算文件的版本号
                    $state = $this->_getResStateVersion($filePath);

    第多个遍历的是js和css目录 第二个遍历是将js目录只怕css目录里的公文都改为路线格局,

    举个例子说获取文件的相对路线 $file帕特h 的值是那样子的:

    /usr/local/apache2/htdocs/project/www/css/home/index.css

    而文件的相对路线$object是那样子的 :

    css/home/index.css

    此地就开头调用$this->_getResStateVersion($file帕特h)来测算文件的本子号

    ——————————-调用_getResStateVersion($filePath) 讲解start————————————————————

    PHP

    /** * 总结文件的版本号,那些是基于总结文件MD5散列值获得版本号 * 只要文件内容更换了,所总结得到的散列值就能够分歧等 * 用于剖断财富文件是不是有变动过 * @param [type] $filePath [description] * @return [type] [description] */ public function _getResStateVersion($filePath) { return base_convert(crc32(md5_file($filePath)), 10, 36); }

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    /**
         * 计算文件的版本号,这个是根据计算文件MD5散列值得到版本号
         * 只要文件内容改变了,所计算得到的散列值就会不一样
         * 用于判断资源文件是否有改动过
         * @param  [type] $filePath [description]
         * @return [type]           [description]
         */
        public function _getResStateVersion($filePath) {
            return base_convert(crc32(md5_file($filePath)), 10, 36);
        }

    ——————————-调用_getResStateVersion($filePath) 讲解end————————————————————-

    要么到版本号后,再看下一段代码,这里开端调用$this->getObjectInfo()方法,这里获得到压缩文件的相对路线$minObject,是还是不是需求压缩$needCompress,版本号$state,文件后缀$extension。

    PHP

    //获取文件的多少个参数值 if (true !== $this->getObjectInfo($object, $minObject, $needCompress, $state, $extension)) { continue; }

    1
    2
    3
    4
    //获取文件的几个参数值
                    if (true !== $this->getObjectInfo($object, $minObject, $needCompress, $state, $extension)) {
                        continue;
                    }

    ——————————调用$this->getObjectInfo() 讲解start————————————————————

    PHP

    /** * 获取财富文件有关消息 * @param [type] $object 能源文件路径(www/css/home/index.css) * @param [type] $minObject 压缩能源文件路线(www/min/css/home/index.ae123a.css) * @param [type] $needCompress 是或不是要求压缩 * @param [type] $state 文件版本号 * @param [type] $extension 文件名后缀 * @return [type] [description] */ public function getObjectInfo($object, &$minObject, &$needCompress, &$state, &$extension) { //获取财富相对路线 $filePath = $this->resRootDir . $object; //判别能源是还是不是存在 if (!file_exists($filePath)) return "能源文件不存在{$filePath}"; //版本号 $state = $this-> _getResStateVersion($filePath); //文件名后缀 $extension = pathinfo($filePath, PATHINFO_EXTENSION); //是或不是要削减 $needCompress = true; //判定能源文件是不是是以 .min.css或许.min.js结尾的 //此类结尾一般都以已收缩过,举个例子jquery.min.js,就无须再压缩了 if (str_end_with($object, '.min.'.$extension, true)) { //压缩后的财富存放路径,放在 /www/min/ 目录下 $minObject = 'min/'.substr($object, 0, strlen($object) - strlen($extension) - 4) . $state .'.'. $extension; $needCompress = false; } else if (in_array($extension, $this->compressResDir)) { //此处是亟需减小的文件目录 $minObject = 'min/'.substr($object, 0, strlen($object) - strlen($extension)) . $state . '.' . $extension; //看看是还是不是是忽略的路径前缀 foreach ($this->compressResIngorePrefix as $v) { if (str_start_with($object, $v, true)) { $needCompress = false; } } } else { $minObject = 'min/'.$object; $needCompress = false; } return true; }

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    /**
         * 获取资源文件相关信息
         * @param  [type] $object       资源文件路径 (www/css/home/index.css)
         * @param  [type] $minObject    压缩资源文件路径 (www/min/css/home/index.ae123a.css)
         * @param  [type] $needCompress 是否需要压缩
         * @param  [type] $state        文件版本号
         * @param  [type] $extension    文件名后缀
         * @return [type]               [description]
         */
        public function getObjectInfo($object, &$minObject, &$needCompress, &$state, &$extension) {
            //获取资源绝对路径
            $filePath = $this->resRootDir . $object;
            //判断资源是否存在
            if (!file_exists($filePath)) return "资源文件不存在{$filePath}";
            //版本号
            $state = $this-> _getResStateVersion($filePath);
            //文件名后缀
            $extension = pathinfo($filePath, PATHINFO_EXTENSION);
            //是否要压缩
            $needCompress = true;
     
            //判断资源文件是否是以 .min.css或者.min.js结尾的
            //此类结尾一般都是已压缩过,例如jquery.min.js,就不必再压缩了
            if (str_end_with($object, '.min.'.$extension, true)) {
                //压缩后的资源存放路径,放在 /www/min/ 目录下
                $minObject = 'min/'.substr($object, 0, strlen($object) - strlen($extension) - 4) . $state .'.'. $extension;
                $needCompress = false;
            } else if (in_array($extension, $this->compressResDir)) {
                //此处是需要压缩的文件目录
                $minObject = 'min/'.substr($object, 0, strlen($object) - strlen($extension)) . $state . '.' . $extension;
                //看看是否是忽略的路径前缀
                foreach ($this->compressResIngorePrefix as $v) {
                    if (str_start_with($object, $v, true)) {
                        $needCompress = false;
                    }
                }
            } else {
                $minObject = 'min/'.$object;
                $needCompress = false;
            }
            return true;
        }

    其一办法里的每一行代码基本上都有注释了,所以就不一句句进行教学了,这里主要看上边包车型地铁判别部分:

    if (str_end_with($object, ‘.min.’.$extension, true)) 那个论断是相比较财富文件路径字串尾部是不是以 .min.$extension 结尾,比如是 jquery.min.js,这种文件本来就是
    削减过的文本,所以就无须再打开削减处理了, $minObject 那个变量存放的是削减后的能源文件路线。
    这里附上str_end_with()函数的代码:

    PHP

    /** * 剖断 subject 是不是以 search结尾, 参数钦赐是或不是忽略大小写 * @param [type] $subject [description] * @param [type] $search [description] * @param boolean $ignore_case [description] * @return [type] [description] */ function str_end_with($subject, $search, $ignore_case = false) { $len2 = strlen($search); if (0 === $len2) return true; $len1 = strlen($subject); if ($len2 > $len1) return false; if ($ignore_case) { return 0 === strcmp(substr($subject, $len1 - $len2), $search); } else { return 0 === strcasecmp(substr($subject, $len1 - $len2), $search); } }

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    /**
         * 判断 subject 是否以 search结尾, 参数指定是否忽略大小写
         * @param  [type]  $subject     [description]
         * @param  [type]  $search      [description]
         * @param  boolean $ignore_case [description]
         * @return [type]               [description]
         */
        function str_end_with($subject, $search, $ignore_case = false) {
            $len2 = strlen($search);
            if (0 === $len2) return true;
            $len1 = strlen($subject);
            if ($len2 > $len1) return false;
            if ($ignore_case) {
                return 0 === strcmp(substr($subject, $len1 - $len2), $search);
            } else {
                return 0 === strcasecmp(substr($subject, $len1 - $len2), $search);
            }
        }

    if (in_array($extension, $this->compressResDir),这几个剖断正是是还是不是是须要管理的四个目录里的。

    然后中间的foreach ($this->compressResIngorePrefix as $v) { if (str_start_with($object, $v, true)) { $needCompress = false; } }

    其一是剖断是或不是是以$this->compressResIngorePrefix属性定义的眼下部分字串发轫的门径,是的话就忽略压缩该能源文件。

    认清到最后else 就是认证该能源文件无需减小了,最终是重临$minObject,$needCompress,$state,$extension这两个变量。

    ——————————-调用$this->getObjectInfo() 讲解end————————————————————-

    到此处延续回来看 compressRes()方法里面包车型地铁代码

    PHP

    //压缩文件的相对路线 $minFilePath = str_replace('\', '/', $this->resRootDir. $minObject); //************此处p决断是最主要片段之一*****************// //判别文件是不是留存且早已改成过 if (isset($resState[$object]) && $resState[$object] == $state && isset($resState[$minObject]) && file_exists($minFilePath)) { continue; }

    1
    2
    3
    4
    5
    6
    7
    8
    //压缩文件的绝对路径
                    $minFilePath = str_replace('\', '/', $this->resRootDir. $minObject);
     
                    //************此处p判断是最重要部分之一*****************//
                    //判断文件是否存在且已经改动过
                    if (isset($resState[$object]) && $resState[$object] == $state && isset($resState[$minObject]) && file_exists($minFilePath)) {
                        continue;
                    }

    这段代码首先是东拼西凑出压缩文件的相对路线,

    随即上边那一个论断是第一的局地,通过那一个推断就能够明白该能源文件是不是被改成过,假使退换过的话,就再一次对该能源文件举办压缩,即使没改动过,就卫冕处理下贰个能源文件。看这里的决断:isset($resState[$object]) && $resState[$object] == $state,这一个决断正是推断该公文路径是还是不是留存  并且文件中对应的版本号和计量出的版本号是或不是还同样;isset($resState[$minObject]) &&file_exists($minFilePath),这一个是剖断压缩文件路线是不是存在,并且该压缩文件是或不是真实存在目录中。

    看下一段代码,假设能走到这一有个别,表明当前的那几个能源文件是被转移过的(代码修改过),那么此时就对文本实行压缩操作了

    PHP

    //确认保证/www/min/目录可写 $this->_ensureWritableDir(dirname($minFilePath)); if ($needCompress) { $this->compressResFileAndSave($filePath, $minFilePath); } else { copy($filePath, $minFilePath); }

    1
    2
    3
    4
    5
    6
    7
    8
    //确保/www/min/目录可写
                    $this->_ensureWritableDir(dirname($minFilePath));
     
                    if ($needCompress) {
                        $this->compressResFileAndSave($filePath, $minFilePath);
                    } else {
                        copy($filePath, $minFilePath);
                    }

    $this->_ensureWritableDir(),此情势是要保管新创设的www/min目录是可写的,这里附上代码:

    ——————————-调用$this->_ensureWritableDir() 讲解start————————————————————-

    PHP

    /** * 确认保证目录可写 * @param [type] $dir [description] * @return [type] [description] */ private function _ensureWritableDir($dir) { if (!file_exists($dir)) { @mkdir($dir, 0777, true); @chmod($dir, 0777); } else if (!is_writable($dir)) { @chmod($dir, 0777); if (!is_writable($dir)) { show_error('目录'.$dir.'不可写'); } } }

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    /**
         * 确保目录可写
         * @param  [type] $dir [description]
         * @return [type]      [description]
         */
        private function _ensureWritableDir($dir) {
            if (!file_exists($dir)) {
                @mkdir($dir, 0777, true);
                @chmod($dir, 0777);
            } else if (!is_writable($dir)) {
                @chmod($dir, 0777);
                if (!is_writable($dir)) {
                    show_error('目录'.$dir.'不可写');
                }
            }
        }

    ——————————-调用$this->_ensureWritableDir() 讲解end————————————————————-

    if ($needCompress),那些决断财富文件是还是不是供给减小,需求的话调用$this->compressResFileAndSave($filePath, $minFilePath);无需的话,直接复制文件到压缩文件路线 copy($filePath, $minFilePath);

    先看$this->compressResFileAndSave()

    ——————————-调用$this->compressResFileAndSave() 讲解start————————————————————-

    PHP

    /** * 将压缩后的财富文件写入到/www/min/下去 * @param [type] $filePath [description] * @param [type] $minFilePath [description] * @return [type] [description] */ private function compressResFileAndSave($filePath, $minFilePath) { if (!file_put_contents($minFilePath, $this->compressResFile($filePath))) { //$CI->exceptions->show_exception("写入文件{$minFilePath}失利"); show_error("写入文件{$minFile帕特h}战败", -1); } } /** * 压缩财富文件 * @param [type] $filePath [description] * @return [type] [description] */ private function compressResFile($filePath) { $extension = strtolower(pathinfo($filePath, PATHINFO_EXTENSION)); if ($extension === 'js') { require_once 'JShrink/Minifier.php'; return JShrinkMinifier::minify(file_get_contents($filePath)); } else if ($extension ==='css') { $content = file_get_contents($filePath); $content = preg_replace('!/*[^*]** ([^/][^*]** )*/!', '', $content); $content = str_replace(["rn", "r", "n"], '', $content); $content = preg_replace('/([{}),;:>])s /', '$1', $content); $content = preg_replace('/s ([{}),;:>])/', '$1', $content); $content = str_replace(';}', '}', $content); return $content; } else { //$CI->exceptions->show_exception("不协助压缩{extension}文件[$filePath]"); show_error("不协理压缩{extension}文件[$filePath]", -1); } }

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    /**
         * 将压缩后的资源文件写入到/www/min/下去
         * @param  [type] $filePath    [description]
         * @param  [type] $minFilePath [description]
         * @return [type]              [description]
         */
        private function compressResFileAndSave($filePath, $minFilePath) {
            if (!file_put_contents($minFilePath, $this->compressResFile($filePath))) {
     
                //$CI->exceptions->show_exception("写入文件{$minFilePath}失败");
                show_error("写入文件{$minFilePath}失败", -1);
            }
        }
     
        /**
         * 压缩资源文件
         * @param  [type] $filePath [description]
         * @return [type]           [description]
         */
        private function compressResFile($filePath) {
            $extension = strtolower(pathinfo($filePath, PATHINFO_EXTENSION));
            if ($extension === 'js') {
                require_once 'JShrink/Minifier.php';
                return JShrinkMinifier::minify(file_get_contents($filePath));
            } else if ($extension ==='css') {
                $content = file_get_contents($filePath);
                $content = preg_replace('!/*[^*]** ([^/][^*]** )*/!', '', $content);
                $content = str_replace(["rn", "r", "n"], '', $content);
                $content = preg_replace('/([{}),;:>])s /', '$1', $content);
                $content = preg_replace('/s ([{}),;:>])/', '$1', $content);
                $content = str_replace(';}', '}', $content);
                return $content;
            } else {
                //$CI->exceptions->show_exception("不支持压缩{extension}文件[$filePath]");
                show_error("不支持压缩{extension}文件[$filePath]", -1);
     
            }
        }

    先削减,再将收缩后的剧情写入到 压缩文件路线里去。

    大家先看下这些压缩方法:

    $this->compressResFile($filePath); 此方法中分两类压缩,第一类时对js文件进行削减,第二类的对css文件进行压缩。先说js压缩,这里是调用贰个JShrink的类,它

    一个用来压缩js文件的PHP类,百度能够找到,调用这一个类的minify()这么些措施就足以减弱了;而css的缩减利用正则替换成缩小,把那多少个空格换行什么的都去掉。到此就减少成功

    了,然后再将削减后的能源写入到对应的压缩文件路线里去。

    ——————————-调用$this->compressResFileAndSave() 讲解end————————————————————-

    紧接着继续看compressRes()那些法子里的代码,这里开首就是保存新的版本号到$resState数组里 $object=>$state,还应该有正是新的削减路径$minObject,而这里$count 的效益是,当那么些轮回四十六次就将 $resState那么些数组写入三遍到 resState.php文件里,这里是由于谨慎思考而已,假使您不加那几个$count的管理这一部分也得以,最终写入三回就行了。

    PHP

    $resState[$object] = $state; $resState[$minObject] = ''; $count ; if ($count == 50) { $this->_saveResState($resState); $count = 0; } } } if($count) $this->_saveResState($resState);

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    $resState[$object] = $state;
                    $resState[$minObject] = '';
                    $count ;
     
                    if ($count == 50) {
                        $this->_saveResState($resState);
                        $count = 0;
                    }
     
                }
            }
            if($count) $this->_saveResState($resState);

    这里看$this->_saveResState($resState),那几个主意正是将$resState数组写入到resState.php文件里去的秘籍。

    ——————————-调用$this->_saveResState($resState) 讲解start————————————————————-

    PHP

    private function _saveResState($resState) { ksort($resState); $content = "<?phpnn$resState = array(n"; foreach ($resState as $k => $v) { $content .= "t '$k' => '$v',n"; } $content .= ");nn"; file_put_contents($this->resStatePath, $content); }

    1
    2
    3
    4
    5
    6
    7
    8
    9
    private function _saveResState($resState) {
            ksort($resState);
            $content = "<?phpnn$resState = array(n";
            foreach ($resState as $k => $v) {
                $content .= "t '$k' => '$v',n";
            }
            $content .= ");nn";
            file_put_contents($this->resStatePath, $content);
        }

    ——————————-调用$this->_saveResState($resState) 讲解end————————————————————-

    拍卖完后,看看所生成的文本,这里一个文件会有七个本子,旧版本未有去除掉,在付出意况下删不删除都没难题,这里怎么不删除旧版本的压缩文件,那就事关到在更新多个应用服务器代码时所要注意的主题素材里。在此小编就多讲授一点啊,简单地比方吗,一般大型项目中的静态财富和模板文件是布局在不相同的机械集群上的,上线的进度中,静态能源和页面文件的安立刻间间隔或者会相当交县长,对于五个大型互连网使用来讲就算在三个非常的小的大运间隔内,都有非常的大可能出现新用户访问,假设旧版本的静态财富删除了,但新本子的静态财富还没安顿变成,那么用户就加载不到该静态财富,结果总之,所以,一般景色下大家会保留旧版本的静态资源,然后等具有片段布置到位了,再经过一定的本子删除掉也没涉及,其实,这么些不必删除也是可以的,你考虑,叁个项目发二次版本,才会调用二遍能源文件收缩方法,它只会对修改过的公文实行生成新版本号的静态文件而已。那个就看个人的做法了。

    新葡亰496net 5

    我们得以展开看看,上面那几个正是削减后的文本的代码了,文件原大小为16K,压缩后大概少了5K,以后是11K,压缩比大约是2/3,假诺在大型项目中,一个复杂点的页面会有相当的大的静态财富文件要加载,通过此措施,大大地提升了加载的速度。(恐怕有些朋友以为压缩个几K也许十几K算什么,完全能够忽略,其实作者想说的是,当您在大型项目中优化品种的时候,能够减少几K的代码,也给网址的脾气进步了一大截)

    新葡亰496net 6

    到此,财富收缩处理就解析实现了。其实,有自然基础的心上人,能够一直看本人享受的百般代码就能够了,假如精通不了,再看笔者上面这一步步的深入分析讲授,作者是处于能看过来此博客的恋人,无论本事是好照旧是稍弱,都能看懂,所以才对代码一步步地张开分析教学。(希望各位多多帮助四哥)

    ————————————————————————————————————————-

    1. 接下去正是上课怎么样替换压缩后的财富文件了。

    这个到Home.php

    PHP

    <?php defined('BASEPATH') OR exit('No direct script access allowed'); class Home extends MY_Controller { public function index() { $this->smartyData['test'] = 111; //这些默许是加载 www/css/home/index.css文件 $this->addResLink('index.css'); //那一个暗中同意是加载www/js/jquery.all.min.js文件 $this->addResLink('/jquery.all.min.js'); //那个默许是加载www/js/index.js文件 $this->addResLink('index.js'); $this->displayView('home/index.tpl'); } }

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    <?php
    defined('BASEPATH') OR exit('No direct script access allowed');
     
    class Home extends MY_Controller {
        public function index() {
            $this->smartyData['test'] = 111;
            //这个默认是加载 www/css/home/index.css文件
            $this->addResLink('index.css');
            //这个默认是加载www/js/jquery.all.min.js文件
            $this->addResLink('/jquery.all.min.js');
            //这个默认是加载www/js/index.js文件
            $this->addResLink('index.js');
            $this->displayView('home/index.tpl');
        }
    }

    地点有加载多个能源文件,大家先看看$this->addResLink();那个法子,那个法子放在My_Controller.php里:

    PHP

    /** * 财富路线 * @param [type] $filePath [description] */ protected function addResLink($filePath) { list($filePath, $query) = explode('?', $filePath . '?'); $extension = strtolower(pathinfo($filePath, PATHINFO_EXTENSION)); foreach ($this->_resLink as $v) { if (false === array_search($filePath, $this->_resLink[$extension])) { $this->_resLink[$extension][] = $query == null ? $filePath : $filePath .'?'. $query; } } return $this; }

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    /**
         * 资源路径
         * @param [type] $filePath [description]
         */
        protected function addResLink($filePath) {
            list($filePath, $query) = explode('?', $filePath . '?');
            $extension = strtolower(pathinfo($filePath, PATHINFO_EXTENSION));
            foreach ($this->_resLink as $v) {
                if (false === array_search($filePath, $this->_resLink[$extension])) {
                    $this->_resLink[$extension][] = $query == null ? $filePath : $filePath .'?'. $query;
                }
            }
     
            return $this;
        }

    这里关键是判断了能源文件是css还是js,然后将其存放在 $this->_resLink那特性子里。

    那正是说这里小编就先附上My_Controller.php这一个父类的有着代码吧

    PHP

    <?php defined('BASEPATH') OR exit('No direct script access allowed'); class MY_Controller extends CI_Controller { public function __construct() { parent::__construct(); //压缩jscss财富文件 $this->compressResHandle(); } //==========================使用SMARTY模板引擎================================// /* 斯马特y母版页文件路线 *新葡亰496net多图片上传程序代码,一个实用的php。/ protected $masterPage = 'default.tpl'; /* 视图像和文字件路线*/ protected $smartyView; /* 要赋值给smarty视图的多少*/ protected $smartyData = []; /* 财富文件*/ protected $_resLink = ['js'=>[], 'css'=>[]]; /** * 使用母版页输出四个视图 * @return [type] [description] */ protected function displayView($viewName = null, $masterPage = null) { //为空则选取默许母版 if ($masterPage == null) $masterPage = $this->masterPage; //获取视图的输出内容 $viewContent = $this->_fetchView($this->smartyData, $viewName, $masterPage); $output = ''; //添加css Link foreach ($this->_resLink['css'] as $v) { $output .= res_link($v); } //内容部分 $output .= $viewContent; //尾部增多js 链接 foreach ($this->_resLink['js'] as $v) { $output .= res_link($v); } //发送最后输出结果以及服务器的 HTTP 头到浏览器 $this->output->_display($output); return $output; } private function _fetchView($smartyData, &$viewName, &$masterPage) { if ($viewName == null) $viewName = $this->smartyView; if (empty($this->smarty)) { require_once SMARTY_DI途达.'Smarty.class.php'; $this->smarty = new 斯玛特y(); $this->smarty->setCompileDir(APPPATH . 'cache/'); $this->smarty->setCacheDir(APPPATH . 'cache/'); } //设置视图真实路线 $this->_getViewDir(true, $viewName, $masterPage, $templateDir); foreach ($smartyData as $k => $v) { $this->smarty->assign($k, $v); } if (empty($masterPage)) { return $this->smarty->fetch($viewName); } else { $this->smarty->assign('VIEW_MAIN', $viewName); return $this->smarty->fetch($masterPage); } } /** * 能源路线 * @param [type] $filePath [description] */ protected function addResLink($filePath) { list($filePath, $query) = explode('?', $filePath . '?'); $extension = strtolower(pathinfo($filePath, PATHINFO_EXTENSION)); foreach ($this->_resLink as $v) { if (false === array_search($filePath, $this->_resLink[$extension])) { $this->_resLink[$extension][] = $query == null ? $filePath : $filePath .'?'. $query; } } return $this; } private function _getViewDir($setTemplateDir, &$viewName, &$masterPage = null, &$templateDir) { if ('/' === $viewName[0]) $viewName = substr($viewName, 1); //是还是不是利用模板,有,则路由到 /views/master_page/*****.tpl下去 if ($masterPage) { $masterPage = '/' === $masterPage[0] ? substr($masterPage, 1) : ('master_page' .'/'. $masterPage); } //是不是设置模板目录 if ($setTemplateDir) { $templateDir = VIEWPATH; $this->smarty->setTemplateDir($templateDir); } } /** * 压缩js、css能源文件(优化) * @return [type] [description] */ private function compressResHandle() { $this->load->library('ResMinifier'); //压缩钦命文件夹下的能源文件 $this->resminifier->compressRes(); } } 点击展开 My_Controller.php

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    <?php
    defined('BASEPATH') OR exit('No direct script access allowed');
     
    class MY_Controller extends CI_Controller {
        public function __construct() {
            parent::__construct();
     
            //压缩jscss资源文件
            $this->compressResHandle();
        }
     
        //==========================使用SMARTY模板引擎================================//
        /* Smarty母版页文件路径 */
        protected $masterPage = 'default.tpl';
        /* 视图文件路径*/
        protected $smartyView;
        /* 要赋值给smarty视图的数据*/
        protected $smartyData = [];
        /* 资源文件*/
        protected $_resLink = ['js'=>[], 'css'=>[]];
     
        /**
         * 使用母版页输出一个视图
         * @return [type] [description]
         */
        protected function displayView($viewName = null, $masterPage = null) {
            //为空则选用默认母版
            if ($masterPage == null) $masterPage = $this->masterPage;
            //获取视图的输出内容
            $viewContent = $this->_fetchView($this->smartyData, $viewName, $masterPage);
     
            $output = '';
     
            //添加css Link
            foreach ($this->_resLink['css'] as $v) {
                $output .= res_link($v);
            }
     
            //内容部分
            $output .= $viewContent;
            //尾部添加js 链接
            foreach ($this->_resLink['js'] as $v) {
                $output .= res_link($v);
            }
            //发送最终输出结果以及服务器的 HTTP 头到浏览器
     
            $this->output->_display($output);
            return $output;
        }
     
        private function _fetchView($smartyData, &$viewName, &$masterPage) {
            if ($viewName == null) $viewName = $this->smartyView;
     
            if (empty($this->smarty)) {
                require_once SMARTY_DIR.'Smarty.class.php';
                $this->smarty = new Smarty();
                $this->smarty->setCompileDir(APPPATH . 'cache/');
                $this->smarty->setCacheDir(APPPATH . 'cache/');
            }
     
            //设置视图真实路径
            $this->_getViewDir(true, $viewName, $masterPage, $templateDir);
     
            foreach ($smartyData as $k => $v) {
                $this->smarty->assign($k, $v);
            }
     
            if (empty($masterPage)) {
                return $this->smarty->fetch($viewName);
            } else {
                $this->smarty->assign('VIEW_MAIN', $viewName);
                return $this->smarty->fetch($masterPage);
            }
        }
     
        /**
         * 资源路径
         * @param [type] $filePath [description]
         */
        protected function addResLink($filePath) {
            list($filePath, $query) = explode('?', $filePath . '?');
            $extension = strtolower(pathinfo($filePath, PATHINFO_EXTENSION));
            foreach ($this->_resLink as $v) {
                if (false === array_search($filePath, $this->_resLink[$extension])) {
                    $this->_resLink[$extension][] = $query == null ? $filePath : $filePath .'?'. $query;
                }
            }
     
            return $this;
        }
     
        private function _getViewDir($setTemplateDir, &$viewName, &$masterPage = null, &$templateDir) {
            if ('/' === $viewName[0]) $viewName = substr($viewName, 1);
     
            //是否使用模板,有,则路由到 /views/master_page/*****.tpl下去
            if ($masterPage) {
                $masterPage = '/' === $masterPage[0] ? substr($masterPage, 1) : ('master_page' .'/'. $masterPage);
            }
     
            //是否设置模板目录
            if ($setTemplateDir) {
                $templateDir = VIEWPATH;
                $this->smarty->setTemplateDir($templateDir);
            }
        }
     
        /**
         * 压缩js、css资源文件(优化)
         * @return [type] [description]
         */
        private function compressResHandle() {
            $this->load->library('ResMinifier');
            //压缩指定文件夹下的资源文件
            $this->resminifier->compressRes();
        }
    }
     
    点击打开 My_Controller.php

    打字与印刷出来 $this->_resLink这几个本性的结构是那样子的:

    PHP

    Array ( [js] => Array ( [0] => /jquery.all.min.js [1] => index.js ) [css] => Array ( [0] => index.css ) )

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    Array
    (
        [js] => Array
            (
                [0] => /jquery.all.min.js
                [1] => index.js
            )
     
        [css] => Array
            (
                [0] => index.css
            )
     
    )

    再回去Home.php里面调用 $this->displayView(‘home/index.tpl’);

    我们看那些措施:

    PHP

    /** * 使用母版页输出二个视图 * @return [type] [description] */ protected function displayView($viewName = null, $masterPage = null) { //为空则选择暗中认可母版 if ($masterPage == null) $masterPage = $this->masterPage; //获取视图的出口内容 $viewContent = $this->_fetchView($this->smartyData, $viewName, $masterPage); $output = ''; //添加css Link foreach ($this->_resLink['css'] as $v) { $output .= res_link($v); } //内容部分 $output .= $viewContent; //尾巴部分增加js 链接 foreach ($this->_resLink['js'] as $v) { $output .= res_link($v); } //发送最后输出结果以及服务器的 HTTP 头到浏览器 $this->output->_display($output); return $output; } private function _fetchView($smartyData, &$viewName, &$masterPage) { if ($viewName == null) $viewName = $this->smartyView; if (empty($this->smarty)) { require_once SMARTY_DI奥迪Q7.'斯Matty.class.php'; $this->smarty = new Smarty(); $this->smarty->setCompileDir(应用软件PATH . 'cache/'); $this->smarty->setCacheDir(APPPATH . 'cache/'); } //设置视图真实路线 $this->_getViewDir(true, $viewName, $masterPage, $templateDir); foreach ($smartyData as $k => $v) { $this->smarty->assign($k, $v); } if (empty($masterPage)) { return $this->smarty->fetch($viewName); } else { $this->smarty->assign('VIEW_MAIN', $viewName); return $this->smarty->fetch($masterPage); } }

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    /**
         * 使用母版页输出一个视图
         * @return [type] [description]
         */
        protected function displayView($viewName = null, $masterPage = null) {
            //为空则选用默认母版
            if ($masterPage == null) $masterPage = $this->masterPage;
            //获取视图的输出内容
            $viewContent = $this->_fetchView($this->smartyData, $viewName, $masterPage);
     
            $output = '';
     
            //添加css Link
            foreach ($this->_resLink['css'] as $v) {
                $output .= res_link($v);
            }
     
            //内容部分
            $output .= $viewContent;
            //尾部添加js 链接
            foreach ($this->_resLink['js'] as $v) {
                $output .= res_link($v);
            }
            //发送最终输出结果以及服务器的 HTTP 头到浏览器
     
            $this->output->_display($output);
            return $output;
        }
     
        private function _fetchView($smartyData, &$viewName, &$masterPage) {
            if ($viewName == null) $viewName = $this->smartyView;
     
            if (empty($this->smarty)) {
                require_once SMARTY_DIR.'Smarty.class.php';
                $this->smarty = new Smarty();
                $this->smarty->setCompileDir(APPPATH . 'cache/');
                $this->smarty->setCacheDir(APPPATH . 'cache/');
            }
     
            //设置视图真实路径
            $this->_getViewDir(true, $viewName, $masterPage, $templateDir);
     
            foreach ($smartyData as $k => $v) {
                $this->smarty->assign($k, $v);
            }
     
            if (empty($masterPage)) {
                return $this->smarty->fetch($viewName);
            } else {
                $this->smarty->assign('VIEW_MAIN', $viewName);
                return $this->smarty->fetch($masterPage);
            }
        }

    这一段代码未有一部分正是调用了斯玛特y模板引擎的剧情,这么些关于斯马特y的知识作者就不讲了,大家能够友善百度,这里根本讲 res_link() 这一个函数,正是经过那一个函数来举行能源文件替换的。先看那一个函数的代码:

    PHP

    /** * 输出 HttpHead 中的能源总是。 css/js 自动推断真实路线 * @param string 文件路线 * @return string */ function res_link($file) { $file = res_path($file, $extension); if ($extension === 'css') { return '<link rel="stylesheet" type="text/css" href="' . $file . '"/>'; } else if ($extension === 'js') { return '<script type="text/javascript" src="'.$file.'"></script>'; } else { return false; } }

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    /**
         * 输出 HttpHead 中的资源连接。 css/js 自动判断真实路径
         * @param  string  文件路径
         * @return string      
         */
        function res_link($file) {
            $file = res_path($file, $extension);
     
            if ($extension === 'css') {
               return '<link rel="stylesheet" type="text/css" href="' . $file . '"/>';
            } else if ($extension === 'js') {
                return '<script type="text/javascript" src="'.$file.'"></script>';
            } else {
                return false;
            }
        }

    此地最关键便是 res_path() 函数了,那个函数能半自动路由能源的真实路线。举个例子:index.css = > css/home/index.css

    该函数最重视的三个功用是替换财富的缩减版本。

    直接看代码:

    PHP

    /** * 智能路由资源实际路线 * @param string 路径 * @param string 扩展名 * @return string 真实路线 */ function res_path($file, &$extension) { //检查是不是留存询问字符串 list($file, $query) = explode('?', $file . '?'); //获得扩张名 $extension = strtolower(pathinfo($file, PATHINFO_EXTENSION)); // $file = str_replace('\', '/', $file); //取妥贴前调控器名 global $class; if ($class == null) exit('can not get class name'); $className = strtolower($class); //此处的条条框框是那样: //举个例子,如若不加 / ,Home调整器对应的格式是: index.css,那么 此处的路线会变成css/home/index.css //要是有 / ,调节器的格式可以是 /main.css,那么这里的路径会形成 css/main.css(公用的css类) if ('/' !== $file[0]) { //index.css => css/home/index.css $object = $extension .'/'. $className .'/' . $file; } else { // /css/main.css 或然 /main.css => css/main.css $object = substr($file, 1); //若object是 main.css ,则自动抬高 增加名目录 => css/main.css if (0 !== strncasecmp($extension, $object, strlen($extension))) { $object = $extension . '/' . $object; } } //资源真实路线 $filepath = WEBROOT.'www/'.$object; //替换压缩版本,那有些逻辑与公事收缩逻辑对应 if (in_array($extension, array('css', 'js'))) { if(!str_start_with($object, 'min/') && file_exists(APPPATH.'libraries/ResMinifier.php')) { require_once APPPATH.'libraries/Res迷你fier.php'; $resminifier = new ResMinifier(); //获取存放财富版本的公文的数组变量 $resState = $resminifier->getResState(); //计算取稳当前文件版本号 $state = $resminifier->_getResStateVersion($filepath); //推断该版本号是不是存在 if (isset($resState[$object])) { //推断是不是是.min.css或.min.js结尾 if (str_end_with($object, '.min.'.$extension)) { //将版本号拼接上去,然后拿走min的文书路线 $minObject = 'min/'.substr($object, 0, strlen($object) - strlen($extension) - 4) . $state . '.' . $extension; } else { //将版本号拼接上去,然后拿走min的公文路线 $minObject = 'min/'.substr($object, 0, strlen($object) - strlen($extension)) . $state . '.' . $extension; } //判别min的路线是或不是留存在$resState里面 if (isset($resState[$minObject])) { $object = $minObject; $query = ''; } } } $file = RES_BASE_URL . $object; } return ($query == null) ? $file : ($file .'?'. $query); }

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    /**
         * 智能路由资源真实路径
         * @param  string      路径
         * @param  string      扩展名
         * @return string       真实路径
         */
        function res_path($file, &$extension) {
            //检查是否存在查询字符串
            list($file, $query) = explode('?', $file . '?');
            //取得扩展名
            $extension = strtolower(pathinfo($file, PATHINFO_EXTENSION));
            //
            $file = str_replace('\', '/', $file);
            //取得当前控制器名
            global $class;
            if ($class == null) exit('can not get class name');
            $className = strtolower($class);
     
            //此处的规则是这样:
            //例如,如果不加 / ,Home控制器对应的格式是: index.css,那么 此处的路径会变成css/home/index.css
            //假如有 / ,控制器的格式可以是 /main.css,那么此处的路径会变成 css/main.css(公用的css类)
            if ('/' !== $file[0]) {
                //index.css => css/home/index.css
                $object = $extension .'/'. $className .'/' . $file;
            } else {
                // /css/main.css 或者 /main.css => css/main.css
                $object = substr($file, 1);
     
                //若object是 main.css ,则自动加上 扩展名目录 => css/main.css
                if (0 !== strncasecmp($extension, $object, strlen($extension))) {
                    $object = $extension . '/' . $object;
                }
            }
            //资源真实路径
            $filepath = WEBROOT.'www/'.$object;
     
            //替换压缩版本,这部分逻辑与文件压缩逻辑对应
            if (in_array($extension, array('css', 'js'))) {
                if(!str_start_with($object, 'min/') && file_exists(APPPATH.'libraries/ResMinifier.php')) {
                    require_once APPPATH.'libraries/ResMinifier.php';
                    $resminifier = new ResMinifier();
                    //获取存放资源版本的文件的数组变量
                    $resState = $resminifier->getResState();
                    //计算得到当前文件版本号
                    $state = $resminifier->_getResStateVersion($filepath);
                    //判断该版本号是否存在
                    if (isset($resState[$object])) {
                        //判断是否是.min.css或.min.js结尾
                        if (str_end_with($object, '.min.'.$extension)) {
                            //将版本号拼接上去,然后得到min的文件路径
                            $minObject = 'min/'.substr($object, 0, strlen($object) - strlen($extension) - 4) . $state . '.' . $extension;
                        } else {
                            //将版本号拼接上去,然后得到min的文件路径
                            $minObject = 'min/'.substr($object, 0, strlen($object) - strlen($extension)) . $state . '.' . $extension;
                        }
                        //判断min的路径是否存在在$resState里面
                         if (isset($resState[$minObject])) {
                            $object = $minObject;
                            $query = '';
                         }
                    }
     
                }
     
                $file = RES_BASE_URL . $object;
            }
     
            return ($query == null) ? $file : ($file .'?'. $query);
     
        }

    代码基本上都给了讲授,方便大家轻便去领会,前边一部分是智能路线css、js财富的门道,前边一部分是替换压缩版本,这一有的的逻辑其实和资源裁减这里的逻辑基本同样,正是通过财富文件路线,进行推断和管理,最终获得财富的滑坡版本的渠道,最终就将能源的回落版本的路线再次来到去,放在'<link rel=”stylesheet” type=”text/css” href=”‘ . $file . ‘”/>’里面。那样  ,就打响地将能源文件路线替换到了缩短版本的能源文件路线,并且在模板输出时,输出的是缩减后的财富文件。

    到此,能源替换的内容就到此疏解甘休。而整一项手艺也深入分析到此。

    三、总结

    在这里小编聚集地附着本博文讲明中的多少个公文代码:

    Home.php

    PHP

    <?php defined('BASEPATH') OR exit('No direct script access allowed'); class Home extends MY_Controller { public function index() { $this->smartyData['test'] = 111; //这几个私下认可是加载 www/css/home/index.css文件 $this->addResLink('index.css'); //那一个暗许是加载www/js/jquery.all.min.js文件 $this->addResLink('/jquery.all.min.js'); //那几个暗中同意是加载www/js/index.js文件 $this->addResLink('index.js'); $this->displayView('home/index.tpl'); } } 点击展开

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    <?php
    defined('BASEPATH') OR exit('No direct script access allowed');
     
    class Home extends MY_Controller {
        public function index() {
            $this->smartyData['test'] = 111;
            //这个默认是加载 www/css/home/index.css文件
            $this->addResLink('index.css');
            //这个默认是加载www/js/jquery.all.min.js文件
            $this->addResLink('/jquery.all.min.js');
            //这个默认是加载www/js/index.js文件
            $this->addResLink('index.js');
            $this->displayView('home/index.tpl');
        }
    }
     
    点击打开

    My_Controller.php

    PHP

    <?php defined('BASEPATH') OR exit('No direct script access allowed'); class MY_Controller extends CI_Controller { public function __construct() { parent::__construct(); //压缩jscss能源文件 $this->compressResHandle(); } //==========================使用SMARTY模板引擎================================// /* 斯马特y母版页文件路线 */ protected $masterPage = 'default.tpl'; /* 视图像和文字件路线*/ protected $smartyView; /* 要赋值给smarty视图的多寡*/ protected $smartyData = []; /* 财富文件*/ protected $_resLink = ['js'=>[], 'css'=>[]]; /** * 使用母版页输出三个视图 * @return [type] [description] */ protected function displayView($viewName = null, $masterPage = null) { //为空则选取私下认可母版 if ($masterPage == null) $masterPage = $this->masterPage; //获取视图的出口内容 $viewContent = $this->_fetchView($this->smartyData, $viewName, $masterPage); $output = ''; //添加css Link foreach ($this->_resLink['css'] as $v) { $output .= res_link($v); } //内容部分 $output .= $viewContent; //后面部分增多js 链接 foreach ($this->_resLink['js'] as $v) { $output .= res_link($v); } //发送最后输出结果以及服务器的 HTTP 头到浏览器 $this->output->_display($output); return $output; } private function _fetchView($smartyData, &$viewName, &$masterPage) { if ($viewName == null) $viewName = $this->smartyView; if (empty($this->smarty)) { require_once SMARTY_DI奥迪Q7.'斯马特y.class.php'; $this->smarty = new Smarty(); $this->smarty->setCompileDir(APPPATH . 'cache/'); $this->smarty->setCacheDir(APPPATH . 'cache/'); } //设置视图真实路线 $this->_getViewDir(true, $viewName, $masterPage, $templateDir); foreach ($smartyData as $k => $v) { $this->smarty->assign($k, $v); } if (empty($masterPage)) { return $this->smarty->fetch($viewName); } else { $this->smarty->assign('VIEW_MAIN', $viewName); return $this->smarty->fetch($masterPage); } } /** * 财富路径 * @param [type] $filePath [description] */ protected function addResLink($filePath) { list($filePath, $query) = explode('?', $filePath . '?'); $extension = strtolower(pathinfo($filePath, PATHINFO_EXTENSION)); foreach ($this->_resLink as $v) { if (false === array_search($filePath, $this->_resLink[$extension])) { $this->_resLink[$extension][] = $query == null ? $filePath : $filePath .'?'. $query; } } return $this; } private function _getViewDir($setTemplateDir, &$viewName, &$masterPage = null, &$templateDir) { if ('/' === $viewName[0]) $viewName = substr($viewName, 1); //是或不是使用模板,有,则路由到 /views/master_page/*****.tpl下去 if ($masterPage) { $masterPage = '/' === $masterPage[0] ? substr($masterPage, 1) : ('master_page' .'/'. $masterPage); } //是或不是设置模板目录 if ($setTemplateDir) { $templateDir = VIEWPATH; $this->smarty->setTemplateDir($templateDir); } } /** * 压缩js、css资源文件(优化) * @return [type] [description] */ private function compressResHandle() { $this->load->library('ResMinifier'); //压缩钦定文件夹下的财富文件 $this->resminifier->compressRes(); } } 点击展开

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    <?php
    defined('BASEPATH') OR exit('No direct script access allowed');
     
    class MY_Controller extends CI_Controller {
        public function __construct() {
            parent::__construct();
     
            //压缩jscss资源文件
            $this->compressResHandle();
        }
     
        //==========================使用SMARTY模板引擎================================//
        /* Smarty母版页文件路径 */
        protected $masterPage = 'default.tpl';
        /* 视图文件路径*/
        protected $smartyView;
        /* 要赋值给smarty视图的数据*/
        protected $smartyData = [];
        /* 资源文件*/
        protected $_resLink = ['js'=>[], 'css'=>[]];
     
        /**
         * 使用母版页输出一个视图
         * @return [type] [description]
         */
        protected function displayView($viewName = null, $masterPage = null) {
            //为空则选用默认母版
            if ($masterPage == null) $masterPage = $this->masterPage;
            //获取视图的输出内容
            $viewContent = $this->_fetchView($this->smartyData, $viewName, $masterPage);
     
            $output = '';
     
            //添加css Link
            foreach ($this->_resLink['css'] as $v) {
                $output .= res_link($v);
            }
     
            //内容部分
            $output .= $viewContent;
            //尾部添加js 链接
            foreach ($this->_resLink['js'] as $v) {
                $output .= res_link($v);
            }
            //发送最终输出结果以及服务器的 HTTP 头到浏览器
     
            $this->output->_display($output);
            return $output;
        }
     
        private function _fetchView($smartyData, &$viewName, &$masterPage) {
            if ($viewName == null) $viewName = $this->smartyView;
     
            if (empty($this->smarty)) {
                require_once SMARTY_DIR.'Smarty.class.php';
                $this->smarty = new Smarty();
                $this->smarty->setCompileDir(APPPATH . 'cache/');
                $this->smarty->setCacheDir(APPPATH . 'cache/');
            }
     
            //设置视图真实路径
            $this->_getViewDir(true, $viewName, $masterPage, $templateDir);
     
            foreach ($smartyData as $k => $v) {
                $this->smarty->assign($k, $v);
            }
     
            if (empty($masterPage)) {
                return $this->smarty->fetch($viewName);
            } else {
                $this->smarty->assign('VIEW_MAIN', $viewName);
                return $this->smarty->fetch($masterPage);
            }
        }
     
        /**
         * 资源路径
         * @param [type] $filePath [description]
         */
        protected function addResLink($filePath) {
            list($filePath, $query) = explode('?', $filePath . '?');
            $extension = strtolower(pathinfo($filePath, PATHINFO_EXTENSION));
            foreach ($this->_resLink as $v) {
                if (false === array_search($filePath, $this->_resLink[$extension])) {
                    $this->_resLink[$extension][] = $query == null ? $filePath : $filePath .'?'. $query;
                }
            }
     
            return $this;
        }
     
        private function _getViewDir($setTemplateDir, &$viewName, &$masterPage = null, &$templateDir) {
            if ('/' === $viewName[0]) $viewName = substr($viewName, 1);
     
            //是否使用模板,有,则路由到 /views/master_page/*****.tpl下去
            if ($masterPage) {
                $masterPage = '/' === $masterPage[0] ? substr($masterPage, 1) : ('master_page' .'/'. $masterPage);
            }
     
            //是否设置模板目录
            if ($setTemplateDir) {
                $templateDir = VIEWPATH;
                $this->smarty->setTemplateDir($templateDir);
            }
        }
     
        /**
         * 压缩js、css资源文件(优化)
         * @return [type] [description]
         */
        private function compressResHandle() {
            $this->load->library('ResMinifier');
            //压缩指定文件夹下的资源文件
            $this->resminifier->compressRes();
        }
    }
     
    点击打开

    ResMinifier.php

    PHP

    <?php defined('BASEPATH') OR exit('No direct script access allowed'); /** * 能源压缩类 */ class ResMinifier { /** 需求减小的财富目录*/ public $compressResDir = ['css', 'js']; /** 忽略压缩的门道,比如此处是js/icon伊始的门道忽略压缩*/ public $compressResIngorePrefix = ['js/icon']; /** 能源根目录*/ public $resRootDir; /** 财富版本文件路线*/ private $resStatePath; public function __construct() { $this->resRootDir = WEBROOT . 'www/'; $this->resStatePath = WEBROOT . 'www/resState.php'; } public function compressRes() { //获取存放版本的财富文件 $resState = $this->getResState(); $count = 0; //开端遍历须求减少的能源目录 foreach ($this->compressResDir as $resDir) { foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator($this->resRootDir . $resDir , FilesystemIterator::SKIP_DOTS)) as $file) { //获取该能源文件的相对路线$filePath = str_replace('\', '/', $file->getRealPath()); //获取文件相对路线 $object = substr($filePath, strlen($this->resRootDir)); //计算文件的本子号 $state = $this->_getResStateVersion($filePath); //获取文件的多少个参数值 if (true !== $this->getObjectInfo($object, $minObject, $needCompress, $state, $extension)) { continue; } //压缩文件的相对路线 $minFilePath = str_replace('\', '/', $this->resRootDir. $minObject); //************此处p推断是最关键部分之一*****************// //判定文件是或不是存在且早已改造过 if (isset($resState[$object]) && $resState[$object] == $state && isset($resState[$minObject]) && file_exists($minFilePath)) { continue; } //确认保障/www/min/目录可写 $this->_ensureWritableDir(dirname($minFilePath)); if ($needCompress) { $this->compressResFileAndSave($filePath, $minFilePath); } else { copy($filePath, $minFilePath); } $resState[$object] = $state; $resState[$minObject] = ''; $count ; if ($count == 50) { $this->_saveResState($resState); $count = 0; } } } if($count) $this->_saveResState($resState); } /** * 获取财富文件有关消息 * @param [type] $object 能源文件路线 (www/css/home/index.css) * @param [type] $minObject 压缩能源文件路径 (www/min/css/home/index.ae123a.css) * @param [type] $needCompress 是还是不是供给压缩 * @param [type] $state 文件版本号 * @param [type] $extension 文件名后缀 * @return [type] [description] */ public function getObjectInfo($object, &$minObject, &$needCompress, &$state, &$extension) { //获取能源相对路径 $filePath = $this->resRootDir . $object; //决断财富是或不是存在 if (!file_exists($filePath)) return "能源文件不设有{$filePath}"; //版本号 $state = $this-> _getResStateVersion($filePath); //文件名后缀 $extension = pathinfo($file帕特h, PATHINFO_EXTENSION); //是不是要削减 $needCompress = true; //判别能源文件是还是不是是以 .min.css或然.min.js结尾的 //此类结尾一般都以已调整和收缩过,举个例子jquery.min.js,就无须再压缩了 if (str_end_with($object, '.min.'.$extension, true)) { //压缩后的财富存放路线,放在 /www/min/ 目录下 $minObject = 'min/'.substr($object, 0, strlen($object) - strlen($extension) - 4) . $state .'.'. $extension; $needCompress = false; } else if (in_array($extension, $this->compressResDir)) { //此处是亟需减小的文件目录 $minObject = 'min/'.substr($object, 0, strlen($object) - strlen($extension)) . $state . '.' . $extension; //看看是还是不是是忽略的路线前缀 foreach ($this->compressResIngorePrefix as $v) { if (str_start_with($object, $v, true)) { $needCompress = false; } } } else { $minObject = 'min/'.$object; $needCompress = false; } return true; } /** * 获取存放财富版本的文书 * 它是位于二个数组里 * $resState = array( * '文件路线' => '对应的本子号', * '文件路线' => '对应的版本号', * '文件路线' => '对应的本子号', * ); * @return [type] [description] */ public function getResState() { if (file_exists($this->resStatePath)) { require $this->resStatePath; return $resState; } return []; } /** * 总计文件的本子号,那个是依靠总结文件MD5散列值获得版本号 * 只要文件内容改换了,所总结获得的散列值就能不平等 * 用于决断财富文件是还是不是有转移过 * @param [type] $filePath [description] * @return [type] [description] */ public function _getResStateVersion($filePath) { return base_convert(crc32(md5_file($filePath)), 10, 36); } /**新葡亰496net, * 确定保证目录可写 * @param [type] $dir [description] * @return [type] [description] */ private function _ensureWritableDir($dir) { if (!file_exists($dir)) { @mkdir($dir, 0777, true); @chmod($dir, 0777); } else if (!is_writable($dir)) { @chmod($dir, 0777); if (!is_writable($dir)) { show_error('目录'.$dir.'不可写'); } } } /** * 将滑坡后的财富文件写入到/www/min/下去 * @param [type] $filePath [description] * @param [type] $minFilePath [description] * @return [type] [description] */ private function compressResFileAndSave($filePath, $minFilePath) { if (!file_put_contents($minFilePath, $this->compressResFile($filePath))) { //$CI->exceptions->show_exception("写入文件{$minFilePath}失利"); show_error("写入文件{$minFilePath}失利", -1); } } /** * 压缩能源文件 * @param [type] $filePath [description] * @return [type] [description] */ private function compressResFile($filePath) { $extension = strtolower(pathinfo($filePath, PATHINFO_EXTENSION)); if ($extension === 'js') { require_once 'JShrink/Minifier.php'; return JShrinkMinifier::minify(file_get_contents($filePath)); } else if ($extension ==='css') { $content = file_get_contents($filePath); $content = preg_replace('!/*[^*]** ([^/][^*]** )*/!', '', $content); $content = str_replace(["rn", "r", "n"], '', $content); $content = preg_replace('/([{}),;:>])s /', '$1', $content); $content = preg_replace('/s ([{}),;:>])/', '$1', $content); $content = str_replace(';}', '}', $content); return $content; } else { //$CI->exceptions->show_exception("不援救压缩{extension}文件[$filePath]"); show_error("不援助压缩{extension}文件[$filePath]", -1); } } private function _saveResState($resState) { ksort($resState); $content = "<?phpnn$resState = array(n"; foreach ($resState as $k => $v) { $content .= "t '$k' => '$v',n"; } $content .= ");nn"; file_put_contents($this->resStatePath, $content); } } 点击展开

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    <?php
    defined('BASEPATH') OR exit('No direct script access allowed');
    /**
    * 资源压缩类
    */
    class ResMinifier {
        /** 需要压缩的资源目录*/
        public $compressResDir = ['css', 'js'];
        /** 忽略压缩的路径,例如此处是js/icon开头的路径忽略压缩*/
        public $compressResIngorePrefix = ['js/icon'];
        /** 资源根目录*/
        public $resRootDir;
        /** 资源版本文件路径*/
        private $resStatePath;
     
        public function __construct() {
            $this->resRootDir = WEBROOT . 'www/';
            $this->resStatePath = WEBROOT . 'www/resState.php';
        }
     
        public function compressRes() {
            //获取存放版本的资源文件
            $resState = $this->getResState();
            $count = 0;
     
            //开始遍历需要压缩的资源目录
            foreach ($this->compressResDir as $resDir) {
                foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator($this->resRootDir . $resDir , FilesystemIterator::SKIP_DOTS)) as $file) {
                    //获取该资源文件的绝对路径
                    $filePath = str_replace('\', '/', $file->getRealPath());
     
                    //获取文件相对路径
                    $object = substr($filePath, strlen($this->resRootDir));
     
                    //计算文件的版本号
                    $state = $this->_getResStateVersion($filePath);
     
                    //获取文件的几个参数值
                    if (true !== $this->getObjectInfo($object, $minObject, $needCompress, $state, $extension)) {
                        continue;
                    }
     
                    //压缩文件的绝对路径
                    $minFilePath = str_replace('\', '/', $this->resRootDir. $minObject);
     
                    //************此处p判断是最重要部分之一*****************//
                    //判断文件是否存在且已经改动过
                    if (isset($resState[$object]) && $resState[$object] == $state && isset($resState[$minObject]) && file_exists($minFilePath)) {
                        continue;
                    }
     
                    //确保/www/min/目录可写
                    $this->_ensureWritableDir(dirname($minFilePath));
     
                    if ($needCompress) {
                        $this->compressResFileAndSave($filePath, $minFilePath);
                    } else {
                        copy($filePath, $minFilePath);
                    }
     
                    $resState[$object] = $state;
                    $resState[$minObject] = '';
                    $count ;
     
                    if ($count == 50) {
                        $this->_saveResState($resState);
                        $count = 0;
                    }
     
                }
            }
            if($count) $this->_saveResState($resState);
        }
     
        /**
         * 获取资源文件相关信息
         * @param  [type] $object       资源文件路径 (www/css/home/index.css)
         * @param  [type] $minObject    压缩资源文件路径 (www/min/css/home/index.ae123a.css)
         * @param  [type] $needCompress 是否需要压缩
         * @param  [type] $state        文件版本号
         * @param  [type] $extension    文件名后缀
         * @return [type]               [description]
         */
        public function getObjectInfo($object, &$minObject, &$needCompress, &$state, &$extension) {
            //获取资源绝对路径
            $filePath = $this->resRootDir . $object;
            //判断资源是否存在
            if (!file_exists($filePath)) return "资源文件不存在{$filePath}";
            //版本号
            $state = $this-> _getResStateVersion($filePath);
            //文件名后缀
            $extension = pathinfo($filePath, PATHINFO_EXTENSION);
            //是否要压缩
            $needCompress = true;
     
            //判断资源文件是否是以 .min.css或者.min.js结尾的
            //此类结尾一般都是已压缩过,例如jquery.min.js,就不必再压缩了
            if (str_end_with($object, '.min.'.$extension, true)) {
                //压缩后的资源存放路径,放在 /www/min/ 目录下
                $minObject = 'min/'.substr($object, 0, strlen($object) - strlen($extension) - 4) . $state .'.'. $extension;
                $needCompress = false;
            } else if (in_array($extension, $this->compressResDir)) {
                //此处是需要压缩的文件目录
                $minObject = 'min/'.substr($object, 0, strlen($object) - strlen($extension)) . $state . '.' . $extension;
                //看看是否是忽略的路径前缀
                foreach ($this->compressResIngorePrefix as $v) {
                    if (str_start_with($object, $v, true)) {
                        $needCompress = false;
                    }
                }
            } else {
                $minObject = 'min/'.$object;
                $needCompress = false;
            }
            return true;
        }
     
        /**
         * 获取存放资源版本的文件
         * 它是放在一个数组里
         * $resState = array(
         *         '文件路径' => '对应的版本号',
         *         '文件路径' => '对应的版本号',
         *         '文件路径' => '对应的版本号',
         *     );
         * @return [type] [description]
         */
        public function getResState() {
            if (file_exists($this->resStatePath)) {
                require $this->resStatePath;
                return $resState;
            }
            return [];
        }
     
        /**
         * 计算文件的版本号,这个是根据计算文件MD5散列值得到版本号
         * 只要文件内容改变了,所计算得到的散列值就会不一样
         * 用于判断资源文件是否有改动过
         * @param  [type] $filePath [description]
         * @return [type]           [description]
         */
        public function _getResStateVersion($filePath) {
            return base_convert(crc32(md5_file($filePath)), 10, 36);
        }
     
        /**
         * 确保目录可写
         * @param  [type] $dir [description]
         * @return [type]      [description]
         */
        private function _ensureWritableDir($dir) {
            if (!file_exists($dir)) {
                @mkdir($dir, 0777, true);
                @chmod($dir, 0777);
            } else if (!is_writable($dir)) {
                @chmod($dir, 0777);
                if (!is_writable($dir)) {
                    show_error('目录'.$dir.'不可写');
                }
            }
        }
     
        /**
         * 将压缩后的资源文件写入到/www/min/下去
         * @param  [type] $filePath    [description]
         * @param  [type] $minFilePath [description]
         * @return [type]              [description]
         */
        private function compressResFileAndSave($filePath, $minFilePath) {
            if (!file_put_contents($minFilePath, $this->compressResFile($filePath))) {
     
                //$CI->exceptions->show_exception("写入文件{$minFilePath}失败");
                show_error("写入文件{$minFilePath}失败", -1);
            }
        }
     
        /**
         * 压缩资源文件
         * @param  [type] $filePath [description]
         * @return [type]           [description]
         */
        private function compressResFile($filePath) {
            $extension = strtolower(pathinfo($filePath, PATHINFO_EXTENSION));
            if ($extension === 'js') {
                require_once 'JShrink/Minifier.php';
                return JShrinkMinifier::minify(file_get_contents($filePath));
            } else if ($extension ==='css') {
                $content = file_get_contents($filePath);
                $content = preg_replace('!/*[^*]** ([^/][^*]** )*/!', '', $content);
                $content = str_replace(["rn", "r", "n"], '', $content);
                $content = preg_replace('/([{}),;:>])s /', '$1', $content);
                $content = preg_replace('/s ([{}),;:>])/', '$1', $content);
                $content = str_replace(';}', '}', $content);
                return $content;
            } else {
                //$CI->exceptions->show_exception("不支持压缩{extension}文件[$filePath]");
                show_error("不支持压缩{extension}文件[$filePath]", -1);
     
            }
        }
     
        private function _saveResState($resState) {
            ksort($resState);
            $content = "<?phpnn$resState = array(n";
            foreach ($resState as $k => $v) {
                $content .= "t '$k' => '$v',n";
            }
            $content .= ");nn";
            file_put_contents($this->resStatePath, $content);
        }
     
    }
     
    点击打开

    Common.php

    PHP

    <?php /** * 输出 HttpHead 中的资源总是。 css/js 自动判别真实路线 * @param string 文件路线 * @return string */ function res_link($file) { $file = res_path($file, $extension); if ($extension === 'css') { return '<link rel="stylesheet" type="text/css" href="' . $file . '"/>'; } else if ($extension === 'js') { return '<script type="text/javascript" src="'.$file.'"></script>'; } else { return false; } } /** * 智能路由能源实际路线 * @param string 路径 * @param string 扩展名 * @return string 真实路线 */ function res_path($file, &$extension) { //检查是否存在询问字符串 list($file, $query) = explode('?', $file . '?'); //猎取增加名 $extension = strtolower(pathinfo($file, PATHINFO_EXTENSION)); // $file = str_replace('\', '/', $file); //取稳妥前调整器名 global $class; if ($class == null) exit('can not get class name'); $className = strtolower($class); //此处的条条框框是那般: //举例,假诺不加 / ,Home调整器对应的格式是: index.css,那么 此处的路线会产生css/home/index.css //借使有 / ,调整器的格式能够是 /main.css,那么这里的路线会造成 css/main.css(公用的css类) if ('/' !== $file[0]) { //index.css => css/home/index.css $object = $extension .'/'. $className .'/' . $file; } else { // /css/main.css 或许 /main.css => css/main.css $object = substr($file, 1); //若object是 main.css ,则自动抬高 扩张名目录 => css/main.css if (0 !== strncasecmp($extension, $object, strlen($extension))) { $object = $extension . '/' . $object; } } //能源真实路线 $filepath = WEBROOT.'www/'.$object; //替换压缩版本,那部分逻辑与公事收缩逻辑对应 if (in_array($extension, array('css', 'js'))) { if(!str_start_with($object, 'min/') && file_exists(APPPATH.'libraries/ResMinifier.php')) { require_once 应用程式PATH.'libraries/ResMinifier.php'; $resminifier = new ResMinifier(); //获取存放能源版本的文本的数组变量 $resState = $resminifier->getResState(); //总括取妥当前文件版本号 $state = $resminifier->_getResStateVersion($filepath); //判定该版本号是还是不是留存 if (isset($resState[$object])) { //剖断是还是不是是.min.css或.min.js结尾 if (str_end_with($object, '.min.'.$extension)) { //将版本号拼接上去,然后拿走min的文件路线 $minObject = 'min/'.substr($object, 0, strlen($object) - strlen($extension) - 4) . $state . '.' . $extension; } else { //将版本号拼接上去,然后拿走min的文本路线 $minObject = 'min/'.substr($object, 0, strlen($object) - strlen($extension)) . $state . '.' . $extension; } //判定min的门道是还是不是存在在$resState里面 if (isset($resState[$minObject])) { $object = $minObject; $query = ''; } } } $file = RES_BASE_URL . $object; } return ($query == null) ? $file : ($file .'?'. $query); } /** * 推断 subject 是否以 search起始, 参数钦定是或不是忽略大小写 * @param [type] $subject [description] * @param [type] $search [description] * @param boolean $ignore_case [description] * @return [type] [description] */ function str_start_with($subject, $search, $ignore_case = false) { $len2 = strlen($search); if (0 === $len2) return true; $len1 = strlen($subject); if ($len1 < $len2) return false; if ($ignore_case) { return 0 === strncmp($subject, $search, $len2); } else { return 0 === strncasecmp($subject, $search, $len2); } } /** * 决断 subject 是不是以 search结尾, 参数钦点是不是忽略大小写 * @param [type] $subject [description] * @param [type] $search [description] * @param boolean $ignore_case [description] * @return [type] [description] */ function str_end_with($subject, $search, $ignore_case = false) { $len2 = strlen($search); if (0 === $len2) return true; $len1 = strlen($subject); if ($len2 > $len1) return false; if ($ignore_case) { return 0 === strcmp(substr($subject, $len1 - $len2), $search); } else { return 0 === strcasecmp(substr($subject, $len1 - $len2), $search); } } 点击张开

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    <?php
        /**
         * 输出 HttpHead 中的资源连接。 css/js 自动判断真实路径
         * @param  string  文件路径
         * @return string      
         */
        function res_link($file) {
            $file = res_path($file, $extension);
     
            if ($extension === 'css') {
               return '<link rel="stylesheet" type="text/css" href="' . $file . '"/>';
            } else if ($extension === 'js') {
                return '<script type="text/javascript" src="'.$file.'"></script>';
            } else {
                return false;
            }
        }
     
        /**
         * 智能路由资源真实路径
         * @param  string      路径
         * @param  string      扩展名
         * @return string       真实路径
         */
        function res_path($file, &$extension) {
            //检查是否存在查询字符串
            list($file, $query) = explode('?', $file . '?');
            //取得扩展名
            $extension = strtolower(pathinfo($file, PATHINFO_EXTENSION));
            //
            $file = str_replace('\', '/', $file);
            //取得当前控制器名
            global $class;
            if ($class == null) exit('can not get class name');
            $className = strtolower($class);
     
            //此处的规则是这样:
            //例如,如果不加 / ,Home控制器对应的格式是: index.css,那么 此处的路径会变成css/home/index.css
            //假如有 / ,控制器的格式可以是 /main.css,那么此处的路径会变成 css/main.css(公用的css类)
            if ('/' !== $file[0]) {
                //index.css => css/home/index.css
                $object = $extension .'/'. $className .'/' . $file;
            } else {
                // /css/main.css 或者 /main.css => css/main.css
                $object = substr($file, 1);
     
                //若object是 main.css ,则自动加上 扩展名目录 => css/main.css
                if (0 !== strncasecmp($extension, $object, strlen($extension))) {
                    $object = $extension . '/' . $object;
                }
            }
            //资源真实路径
            $filepath = WEBROOT.'www/'.$object;
     
            //替换压缩版本,这部分逻辑与文件压缩逻辑对应
            if (in_array($extension, array('css', 'js'))) {
                if(!str_start_with($object, 'min/') && file_exists(APPPATH.'libraries/ResMinifier.php')) {
                    require_once APPPATH.'libraries/ResMinifier.php';
                    $resminifier = new ResMinifier();
                    //获取存放资源版本的文件的数组变量
                    $resState = $resminifier->getResState();
                    //计算得到当前文件版本号
                    $state = $resminifier->_getResStateVersion($filepath);
                    //判断该版本号是否存在
                    if (isset($resState[$object])) {
                        //判断是否是.min.css或.min.js结尾
                        if (str_end_with($object, '.min.'.$extension)) {
                            //将版本号拼接上去,然后得到min的文件路径
                            $minObject = 'min/'.substr($object, 0, strlen($object) - strlen($extension) - 4) . $state . '.' . $extension;
                        } else {
                            //将版本号拼接上去,然后得到min的文件路径
                            $minObject = 'min/'.substr($object, 0, strlen($object) - strlen($extension)) . $state . '.' . $extension;
                        }
                        //判断min的路径是否存在在$resState里面
                         if (isset($resState[$minObject])) {
                            $object = $minObject;
                            $query = '';
                         }
                    }
     
                }
     
                $file = RES_BASE_URL . $object;
            }
     
            return ($query == null) ? $file : ($file .'?'. $query);
     
        }
     
        /**
         * 判断 subject 是否以 search开头, 参数指定是否忽略大小写
         * @param  [type]  $subject     [description]
         * @param  [type]  $search      [description]
         * @param  boolean $ignore_case [description]
         * @return [type]               [description]
         */
        function str_start_with($subject, $search, $ignore_case = false) {
            $len2 = strlen($search);
            if (0 === $len2) return true;
            $len1 = strlen($subject);
            if ($len1 < $len2) return false;
            if ($ignore_case) {
                return 0 === strncmp($subject, $search, $len2);
            } else {
                return 0 === strncasecmp($subject, $search, $len2);
            }
        }
     
        /**
         * 判断 subject 是否以 search结尾, 参数指定是否忽略大小写
         * @param  [type]  $subject     [description]
         * @param  [type]  $search      [description]
         * @param  boolean $ignore_case [description]
         * @return [type]               [description]
         */
        function str_end_with($subject, $search, $ignore_case = false) {
            $len2 = strlen($search);
            if (0 === $len2) return true;
            $len1 = strlen($subject);
            if ($len2 > $len1) return false;
            if ($ignore_case) {
                return 0 === strcmp(substr($subject, $len1 - $len2), $search);
            } else {
                return 0 === strcasecmp(substr($subject, $len1 - $len2), $search);
            }
        }
     
    点击打开

    $resState.php(里面包车型大巴代码是自动生成的)

    XHTML

    <?php $resState = array( 'css/home/index.css' => 'gwy933', 'js/echarts-all.min.js' => 'wqrf1c', 'js/home/index.js' => 's2z6f5', 'js/icon.js' => 'pgcyih', 'js/icon_home.js' => 'zhl9iu', 'js/ion.rangeSlider.min.js' => 'akq381', 'js/jquery-ui-autocomplete.js' => '8nzacv', 'js/jquery-ui.min.js' => 'i6tw8z', 'js/jquery.all.min.js' => 'd2w76v', 'js/jquery.city.js' => 'toxdrf', 'js/jquery.easydropdown.min.js' => '2ni3i0', 'js/jquery.matrix.js' => '3vrqkk', 'js/jquery.mobile.all.min.js' => 'ernu7r', 'js/jquery.qrcode.min.js' => 'yuhnsj', 'js/jquery.tinyscrollbar.min.js' => 'oakk3c', 'js/mobiscroll.custom.min.js' => 'kn8h2e', 'js/store.min.js' => 'n50jwr', 'js/swiper.animate1.0.2.min.js' => 'mm27zc', 'js/swiper.min.js' => 'jicwhh', 'min/css/home/index.6a4e83eb.css' => '', 'min/css/home/index.gwy933.css' => '', 'min/css/home/index.puzbnf.css' => '', 'min/css/home/index.thv8x7.css' => '', 'min/js/echarts-all.76025ee0.js' => '', 'min/js/echarts-all.wqrf1c.js' => '', 'min/js/home/index.65363d41.js' => '', 'min/js/home/index.s2z6f5.js' => '', 'min/js/icon.5bbd4db9.js' => '', 'min/js/icon.pgcyih.js' => '', 'min/js/icon_home.7fe74076.js' => '', 'min/js/icon_home.zhl9iu.js' => '', 'min/js/ion.rangeSlider.261d8ed1.js' => '', 'min/js/ion.rangeSlider.akq381.js' => '', 'min/js/jquery-ui-autocomplete.1f3bb62f.js' => '', 'min/js/jquery-ui-autocomplete.8nzacv.js' => '', 'min/js/jquery-ui.418e9683.js' => '', 'min/js/jquery-ui.i6tw8z.js' => '', 'min/js/jquery.all.2f248267.js' => '', 'min/js/jquery.all.d2w76v.js' => '', 'min/js/jquery.city.6b036feb.js' => '', 'min/js/jquery.city.toxdrf.js' => '', 'min/js/jquery.easydropdown.2ni3i0.js' => '', 'min/js/jquery.easydropdown.98fa138.js' => '', 'min/js/jquery.matrix.3vrqkk.js' => '', 'min/js/jquery.matrix.dfe2a44.js' => '', 'min/js/jquery.mobile.all.3539ebb7.js' => '', 'min/js/jquery.mobile.all.ernu7r.js' => '', 'min/js/jquery.qrcode.7d9738b3.js' => '', 'min/js/jquery.qrcode.yuhnsj.js' => '', 'min/js/jquery.tinyscrollbar.578e4cb8.js' => '', 'min/js/jquery.tinyscrollbar.oakk3c.js' => '', 'min/js/mobiscroll.custom.4a684f66.js' => '', 'min/js/mobiscroll.custom.kn8h2e.js' => '', 'min/js/store.536545cb.js' => '', 'min/js/store.n50jwr.js' => '', 'min/js/swiper.4650ad75.js' => '', 'min/js/swiper.animate1.0.2.517f82e8.js' => '', 'min/js/swiper.animate1.0.2.mm27zc.js' => '', 'min/js/swiper.jicwhh.js' => '', ); 点击张开

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    <?php
     
    $resState = array(
         'css/home/index.css' => 'gwy933',
         'js/echarts-all.min.js' => 'wqrf1c',
         'js/home/index.js' => 's2z6f5',
         'js/icon.js' => 'pgcyih',
         'js/icon_home.js' => 'zhl9iu',
         'js/ion.rangeSlider.min.js' => 'akq381',
         'js/jquery-ui-autocomplete.js' => '8nzacv',
         'js/jquery-ui.min.js' => 'i6tw8z',
         'js/jquery.all.min.js' => 'd2w76v',
         'js/jquery.city.js' => 'toxdrf',
         'js/jquery.easydropdown.min.js' => '2ni3i0',
         'js/jquery.matrix.js' => '3vrqkk',
         'js/jquery.mobile.all.min.js' => 'ernu7r',
         'js/jquery.qrcode.min.js' => 'yuhnsj',
         'js/jquery.tinyscrollbar.min.js' => 'oakk3c',
         'js/mobiscroll.custom.min.js' => 'kn8h2e',
         'js/store.min.js' => 'n50jwr',
         'js/swiper.animate1.0.2.min.js' => 'mm27zc',
         'js/swiper.min.js' => 'jicwhh',
         'min/css/home/index.6a4e83eb.css' => '',
         'min/css/home/index.gwy933.css' => '',
         'min/css/home/index.puzbnf.css' => '',
         'min/css/home/index.thv8x7.css' => '',
         'min/js/echarts-all.76025ee0.js' => '',
         'min/js/echarts-all.wqrf1c.js' => '',
         'min/js/home/index.65363d41.js' => '',
         'min/js/home/index.s2z6f5.js' => '',
         'min/js/icon.5bbd4db9.js' => '',
         'min/js/icon.pgcyih.js' => '',
         'min/js/icon_home.7fe74076.js' => '',
         'min/js/icon_home.zhl9iu.js' => '',
         'min/js/ion.rangeSlider.261d8ed1.js' => '',
         'min/js/ion.rangeSlider.akq381.js' => '',
         'min/js/jquery-ui-autocomplete.1f3bb62f.js' => '',
         'min/js/jquery-ui-autocomplete.8nzacv.js' => '',
         'min/js/jquery-ui.418e9683.js' => '',
         'min/js/jquery-ui.i6tw8z.js' => '',
         'min/js/jquery.all.2f248267.js' => '',
         'min/js/jquery.all.d2w76v.js' => '',
         'min/js/jquery.city.6b036feb.js' => '',
         'min/js/jquery.city.toxdrf.js' => '',
         'min/js/jquery.easydropdown.2ni3i0.js' => '',
         'min/js/jquery.easydropdown.98fa138.js' => '',
         'min/js/jquery.matrix.3vrqkk.js' => '',
         'min/js/jquery.matrix.dfe2a44.js' => '',
         'min/js/jquery.mobile.all.3539ebb7.js' => '',
         'min/js/jquery.mobile.all.ernu7r.js' => '',
         'min/js/jquery.qrcode.7d9738b3.js' => '',
         'min/js/jquery.qrcode.yuhnsj.js' => '',
         'min/js/jquery.tinyscrollbar.578e4cb8.js' => '',
         'min/js/jquery.tinyscrollbar.oakk3c.js' => '',
         'min/js/mobiscroll.custom.4a684f66.js' => '',
         'min/js/mobiscroll.custom.kn8h2e.js' => '',
         'min/js/store.536545cb.js' => '',
         'min/js/store.n50jwr.js' => '',
         'min/js/swiper.4650ad75.js' => '',
         'min/js/swiper.animate1.0.2.517f82e8.js' => '',
         'min/js/swiper.animate1.0.2.mm27zc.js' => '',
         'min/js/swiper.jicwhh.js' => '',
    );
     
    点击打开

     

    别的附上JShrink那些PHP类的链接给咱们下载 

    假如大家依旧感觉不够OK的话,笔者平昔将以此实验项目打包供大家下载下来学习和询问:

    四、结语

    最后本人来分享大家线上项指标求实贯彻方案:

    大家的体系分线上情况、开拓条件和测试碰到,在开垦和测试意况中,大家每二遍访问都会调用压缩文件的接口,然后再对转移的财富文件的轻重是要做决断的,若是缩减后文件过小,将供给将该能源文件的代码合并到其余能源文件里去,以此缩短不须求的HTTP请求(因为文件太小,财富的下载时间远远低于HTTP请求响应所开销的时日);另二个是图片的管理,全部图片都要透过压缩本领透过(比如在:  那个网址去缩短图片),在PC端,倘诺是小Logo的话,使用图片合并的方法实行优化,详细情形可参看本身的那篇博文:http://www.cnblogs.com/it-cen/p/4618954.html    而在wap端的图样管理利用的是base64编码方式来拍卖图片,详细情况能够参照他事他说加以考察本身的那篇博文:  ,当页面输出时,会利用redis来缓存页面(为什么用内部存款和储蓄器来缓存而不是使用页面缓存,这一个今后再享受给大家)。假使是线上景况,每发叁次版本,才会调用一下能源文件收缩这些接口,并且线上的静态财富(css、js、图片)是存放在在Ali云的OSS里的,与大家的应用服务器是分别的。那是大家线上项目标一局地优消除决方案,当然了,还会有越来越多优化才具,作者会在随后各类计算和享用出去,方便大家共同念书和交换。

    此番博文就享受到此,感激观望此博文的相恋的人们。

    1 赞 1 收藏 评论

    新葡亰496net 7

    文本上传例子

    class html
    {
    var $dir; //dir for the htmls(without/)
    var $rootdir; //root of html files(without/):html
    var $name; //html文件存放路线
    var $dirname; //钦命的文本夹名称
    var $url; //获取html文件消息的来源网页地址
    var $time; //html文件消息填加时的年华
    var $dirtype; //目录存放形式:year,month,,,,
    var $nametype; //html文件命名方式:name

    此间是缘于网上朋友的三个落到实处的文本上传类代码,大家详细的牵线了各类变量的用处,上边看看啊,有亟待可以参照一下。

    <?php
    /**
    * 邮件类
    * Enter description here ...
    * @author df
    * Mail::getMail()->sendMail();
    *
    */
    class Mail{

     代码如下

    function html($nametype='name',$dirtype='year',$rootdir='html')

    <?php教程
     /**
      * 文件上传类
      */
     class uploadFile {

      public $max_size = '一千000';//设置上传文件大小
      public $file_name = 'date';//重命名格局表示以时间命名,别的则动用予以的称谓
      public $allow_types;//允许上传的文书扩大名,不一致文件类型用“|”隔开分离
      public $errmsg = '';//错误消息
      public $uploaded = '';//上传后的文本名(包含文件路径)
      public $save_path;//上传文件保留路线
      private $files;//提交的等待上传文件
      private $file_type = array();//文件类型
      private $ext = '';//上传文件增添名

      /**
       * 构造函数,初步化类
       * @access public
       * @param string $file_name 上传后的公文名
       * @param string $save_path 上传的对象文件夹
       */
      public function __construct($save_path = './upload/',$file_name = 'date',$allow_types = '') {
      $this->file_name   = $file_name;//重命名格局意味着以时间命名,其余则选取予以的名称
      $this->save_path   = (preg_match('//$/',$save_path)) ? $save_path : $save_path . '/';
      $this->allow_types = $allow_types == '' ? 'jpg|gif|png|zip|rar' : $allow_types;
      }

      /**
       * 上传文件
       * @access public
       * @param $files 等待上传的文件(表单传来的$_FILES[])
       * @return boolean 重临布尔值
       */
     public function upload_file($files) {
      $name = $files['name'];
      $type = $files['type'];
      $size = $files['size'];
      $tmp_name = $files['tmp_name'];
      $error = $files['error'];

      switch ($error) {
       case 0 : $this->errmsg = '';
        break;
       case 1 : $this->errmsg = '超越了php.ini普通话件大小';
        break;
       case 2 : $this->errmsg = '超过了MAX_FILE_SIZE 选项钦点的公文大小';
        break;
           case 3 : $this->errmsg = '文件唯有部分被上传';
        break;
       case 4 : $this->errmsg = '没有公文被上传';
        break;
       case 5 : $this->errmsg = '上传文件大小为0';
        break;
          default : $this->errmsg = '上传文件失利!';
        break;
       }
      if($error == 0 && is_uploaded_file($tmp_name)) {
       //检查评定文件类型
       if($this->check_file_type($name) == FALSE){
        return FALSE;
       }
       //检查实验文件大小
       if($size > $this->max_size){
        $this->errmsg = '上传文件<font color=red>'.$name.'</font>太大,最大支撑<font color=red>'.ceil($this->max_size/1024).'</font>kb的文件';
        return FALSE;
       }
       $this->set_save_path();//设置文件存放路线
       $new_name = $this->file_name != 'date' ? $this->file_name.'.'.$this->ext : date('YmdHis').'.'.$this->ext;//设置新文件名
       $this->uploaded = $this->save_path.$new_name;//上传后的文件名
       //移动文件
       if(move_uploaded_file($tmp_name,$this->uploaded)){
        $this->errmsg = '文件<font color=red>'.$this->uploaded.'</font>上传成功!';
        return TRUE;
       }else{
        $this->errmsg = '文件<font color=red>'.$this->uploaded.'</font>上传失利!';
        return FALSE;
       }

      }
     }

      /**
       * 检查上传文件类型
       * @access public
       * @param string $filename 等待检查的文书名
       * @return 要是检查通过再次来到TRUE 未通过则赶回FALSE和谬误音信
       */
        public function check_file_type($filename){
      $ext = $this->get_file_type($filename);
      $this->ext = $ext;
        $allow_types = explode('|',$this->allow_types);//分割允许上传的公文扩张名字为数组
        //echo $ext;
        //检查上传文件增加名是或不是在请允许上传的公文扩大名中
        if(in_array($ext,$allow_types)){
         return TRUE;
        }else{
         $this->errmsg = '上传文件<font color=red>'.$filename.'</font>类型错误,只扶助上传<font color=red>'.str_replace('|',',',$this->allow_types).'</font>等文件类型!';
         return FALSE;
        }
        }

        /**
         * 取得文件类型
         * @access public
         * @param string $filename 要拿走文件类型的靶子文件名
         * @return string 文件类型
         */
        public function get_file_type($filename){
         $info = pathinfo($filename);
         $ext = $info['extension'];
         return $ext;
        }

     /**
      * 设置文件上传后的保存路线
      */
     public function set_save_path(){
      $this->save_path = (preg_match('//$/',$this->save_path)) ? $this->save_path : $this->save_path . '/';
      if(!is_dir($this->save_path)){
       //假如目录不存在,成立目录
       $this->set_dir();
      }
     }


     /**
      * 成立目录
      * @access public
      * @param string $dir 要创建目录的门道
      * @return boolean 退步时回来错误音讯和FALSE
      */
     public function set_dir($dir = null){
      //检查路径是不是存在
      if(!$dir){
       $dir = $this->save_path;
      }
      if(is_dir($dir)){
       $this->errmsg = '须要创制的公文夹已经存在!';
      }
      $dir = explode('/', $dir);
      foreach($dir as $v){
       if($v){
        $d .= $v . '/';
        if(!is_dir($d)){
         $state = mkdir($d, 0777);
         if(!$state)
          $this->errmsg = '在开立目录<font color=red>' . $d . '时出错!';
        }
       }
      }
      return true;
     }
     }

    /*************************************************
     * 图片管理类
     *
     * 能够对图纸张开转换缩略图,打水印等操作
     * 本类暗许编码为UTF8 借使要在GBK下选取请将img_mark方法中打汉语字符串水印iconv注脚去掉
     *
     * 由于UTF8汉字和英文字母大小(像素)不佳分明,在中国和英国文混合出现太多时可能会冒出字符串偏左
     * 或偏右,请遵照项目条件对get_mark_xy方法中的$strc_w = strlen($this->mark_str)*7 5进
     * 行调整
     * 供给GD库援助,为越来越好利用本类推荐应用GD库2.0
     *
     * @author kickflip@php100 QQ263340607
     *************************************************/

     class uploadImg extends uploadFile {

     public $mark_str = 'kickflip@php100';  //水印字符串
     public $str_r = 0; //字符串颜色Murano
     public $str_g = 0; //字符串颜色G
     public $str_b = 0; //字符串颜色B
     public $mark_ttf = './upload/SIMSUN.TTC'; //水印文字字体文件(包罗路线)
     public $mark_logo = './upload/logo.png';    //水印图片
     public $resize_h;//生成缩略图高
     public $resize_w;//生成缩略图宽
     public $source_img;//源图片文件
     public $dst_path = './upload/';//缩略图像和文字件存放目录,不填则为源图片存放目录

     /**
      * 生成缩略图 生成后的图
      * @access public
      * @param integer $w 收缩后图片的宽(px)
      * @param integer $h 减少后图片的高(px)
      * @param string $source_img 源图片(路径 文件名)
      */
     public function img_resized($w,$h,$source_img = NULL){
      $source_img = $source_img == NULL ? $this->uploaded : $source_img;//获得源文件的地址,假如为空则默以为上次上传的图样
      if(!is_file($source_img)) { //检查源图片是不是存在
       $this->errmsg = '文件'.$source_img.'不存在';
       return FALSE;
      }
      $this->source_img = $source_img;
      $img_info = getimagesize($source_img);
      $source = $this->img_create($source_img); //创设源图片
      $this->resize_w = $w;
      $this->resize_h = $h;
      $thumb = imagecreatetruecolor($w,$h);
      imagecopyresized($thumb,$source,0,0,0,0,$w,$h,$img_info[0],$img_info[1]);//生成缩略图片
      $dst_path = $this->dst_path == '' ? $this->save_path : $this->dst_path; //取得指标文件夹路线
      $dst_path = (preg_match('//$/',$dst_path)) ? $dst_path : $dst_path . '/';//将指标文件夹后拉长/
      if(!is_dir($dst_path)) $this->set_dir($dst_path); //假使不存在指标文件夹则开创
      $dst_name = $this->set_newname($source_img);
      $this->img_output($thumb,$dst_name);//输出图片
      imagedestroy($source);
      imagedestroy($thumb);
     }

     /**
      *打水印
      *@access public
      *@param string $source_img 源图片路线 文件名
      *@param integer $mark_type 水印类型(1为英文字符串,2为汉语字符串,3为图片logo,默感到英文字符串)
      *@param integer $mark_postion 水印地方(1为左下角,2为右下角,3为左上角,4为右上角,默以为右下角);
      *@return 打上水印的图形
      */
     public function img_mark($source_img = NULL,$mark_type = 1,$mark_postion = 2) {
      $source_img = $source_img == NULL ? $this->uploaded : $source_img;//取得源文件的地方,假如为空则默以为上次上传的图形
      if(!is_file($source_img)) { //检查源图片是不是存在
       $this->errmsg = '文件'.$source_img.'不存在';
       return FALSE;
      }
      $this->source_img = $source_img;
      $img_info = getimagesize($source_img);
      $source = $this->img_create($source_img); //创制源图片
      $mark_xy = $this->get_mark_xy($mark_postion);//获得水印地方
      $mark_color = imagecolorallocate($source,$this->str_r,$this->str_g,$this->str_b);

      switch($mark_type) {

       case 1 : //加英文字符串水印
       $str = $this->mark_str;
       imagestring($source,5,$mark_xy[0],$mark_xy[1],$str,$mark_color);
       $this->img_output($source,$source_img);
       break;

                case 2 : //加普通话字符串水印
                if(!is_file($this->mark_ttf)) { //检查字体文件是还是不是留存
        $this->errmsg = '打水印战败:字体文件'.$this->mark_ttf.'不存在!';
       return FALSE;
       }
       $str = $this->mark_str;
       //$str = iconv('gbk','utf-8',$str);//调换字符编码 假设利用GBK编码请去掉此行注释
       imagettftext($source,12,0,$mark_xy[2],$mark_xy[3],$mark_color,$this->mark_ttf,$str);
       $this->img_output($source,$source_img);
       break;

       case 3 : //加图片水印
       if(is_file($this->mark_logo)){  //假使存在水印logo的图样则获得logo图片的骨干消息,不存在则脱离
        $logo_info = getimagesize($this->mark_logo);
       }else{
        $this->errmsg = '打水印战败:logo文件'.$this->mark_logo.'不存在!';
        return FALSE;
       }

       $logo_info = getimagesize($this->mark_logo);
       if($logo_info[0]>$img_info[0] || $logo_info[1]>$img_info[1]) { //即使源图片小于logo大小则脱离
        $this->errmsg = '打水印战败:源图片'.$this->source_img.'比'.$this->mark_logo.'小!';
        return FALSE;
       }

       $logo = $this->img_create($this->mark_logo);
       imagecopy ( $source, $logo, $mark_xy[4], $mark_xy[5], 0, 0, $logo_info[0], $logo_info[1]);
       $this->img_output($source,$source_img);
       break;

       default: //别的则为文字图片
       $str = $this->mark_str;
       imagestring($source,5,$mark_xy[0],$mark_xy[1],$str,$mark_color);
       $this->img_output($source,$source_img);
       break;
      }
      imagedestroy($source);
     }

     /**
      * 获得水印地方
      * @access private
      * @param integer $mark_postion 水印的地点(1为左下角,2为右下角,3为左上角,4为右上角,别的为右下角)
      * @return array $mark_xy 水印地方的坐标(索引0为英文字符串水印坐标X,索引1为英文字符串水印坐标Y,
      * 索引2为中文字符串水印坐标X,索引3为华语字符串水印坐标Y,索引4为水印图片坐标X,索引5为水印图片坐标Y)
      */
     private function get_mark_xy($mark_postion){
      $img_info = getimagesize($this->source_img);

      $stre_w = strlen($this->mark_str)*9 5 ; //水印英文字符串的长度(px)(5号字的英文字符大小约为9px 为了美观再加5px)
      //(12号字的粤语字符大小为12px,在utf8里三个汉字长度为3个字节一个字节4px 而三个英文字符长度二个字节大小大概为9px
      // 为了在中国和英国文混合的情事下显得完全 设它的长短为字节数*7px)
      $strc_w = strlen($this->mark_str)*7 5 ; //水印中文字符串的长短(px)

      if(is_file($this->mark_logo)){ //假使存在水印logo的图纸则收获logo图片的骨干消息
       $logo_info = getimagesize($this->mark_logo);
      }

      //由于imagestring函数和imagettftext函数中对于字符串开第二个人置不一致所以英文和中文字符串的Y地点也迥然不一致
      //imagestring函数是从文字的左上角为参照 imagettftext函数是从文字左下角为参照他事他说加以考查
      switch($mark_postion){

       case 1: //地方左下角
       $mark_xy[0] = 5; //水印英文字符串坐标X
       $mark_xy[1] = $img_info[1]-20;//水印英文字符串坐标Y
       $mark_xy[2] = 5; //水印普通话字符串坐标X
       $mark_xy[3] = $img_info[1]-5;//水印普通话字符串坐标Y
       $mark_xy[4] = 5;//水印图片坐标X
       $mark_xy[5] = $img_info[1]-$logo_info[1]-5;//水印图片坐标Y
       break;

       case 2: //地点右下角
       $mark_xy[0] = $img_info[0]-$stre_w; //水印英文字符串坐标X
       $mark_xy[1] = $img_info[1]-20;//水印英文字符串坐标Y
       $mark_xy[2] = $img_info[0]-$strc_w; //水印中文字符串坐标X
       $mark_xy[3] = $img_info[1]-5;//水印普通话字符串坐标Y
       $mark_xy[4] = $img_info[0]-$logo_info[0]-5;//水印图片坐标X
       $mark_xy[5] = $img_info[1]-$logo_info[1]-5;//水印图片坐标Y
       break;

       case 3: //地点左上角
       $mark_xy[0] = 5; //水印英文字符串坐标X
       $mark_xy[1] = 5;//水印英文字符串坐标Y
       $mark_xy[2] = 5; //水印普通话字符串坐标X
       $mark_xy[3] = 15;//水印汉语字符串坐标Y
       $mark_xy[4] = 5;//水印图片坐标X
       $mark_xy[5] = 5;//水印图片坐标Y
       break;

       case 4: //地方右上角
       $mark_xy[0] = $img_info[0]-$stre_w; //水印英文字符串坐标X
       $mark_xy[1] = 5;//水印英文字符串坐标Y
       $mark_xy[2] = $img_info[0]-$strc_w; //水印中文字符串坐标X
       $mark_xy[3] = 15;//水印汉语字符串坐标Y
       $mark_xy[4] = $img_info[0]-$logo_info[0]-5;//水印图片坐标X
       $mark_xy[5] = 5;//水印图片坐标Y
       break;

       default : //别的默许为右下角
       $mark_xy[0] = $img_info[0]-$stre_w; //水印英文字符串坐标X
       $mark_xy[1] = $img_info[1]-5;//水印英文字符串坐标Y
       $mark_xy[2] = $img_info[0]-$strc_w; //水印汉语字符串坐标X
       $mark_xy[3] = $img_info[1]-15;//水印中文字符串坐标Y
       $mark_xy[4] = $img_info[0]-$logo_info[0]-5;//水印图片坐标X
       $mark_xy[5] = $img_info[1]-$logo_info[1]-5;//水印图片坐标Y
       break;
      }
      return $mark_xy;
     }

     /**
      * 成立源图片
      * @access private
      * @param string $source_img 源图片(路径 文件名)
      * @return img 从指标文件新建的图像
      */
     private function img_create($source_img) {
      $info = getimagesize($source_img);
      switch ($info[2]){
                case 1:
                if(!function_exists('imagecreatefromgif')){
                 $source = @imagecreatefromjpeg($source_img);
                }else{
                 $source = @imagecreatefromgif($source_img);
                }
                break;
                case 2:
                $source = @imagecreatefromjpeg($source_img);
                break;
                case 3:
                $source = @imagecreatefrompng($source_img);
                break;
                case 6:
                $source = @imagecreatefromwbmp($source_img);
                break;
                default:
       $source = FALSE;
       break;
            }
      return $source;
     }

     /**
      * 重命名图片
      * @access private
      * @param string $source_img 源图片路线 文件名
      * @return string $dst_name 重命名后的图纸名(路线 文件名)
      */
     private function set_newname($sourse_img) {
      $info = pathinfo($sourse_img);
      $new_name = $this->resize_w.'_'.$this->resize_h.'_'.$info['basename'];//将文件名修改为:宽_高_文件名
      if($this->dst_path == ''){ //假使存放缩略图路线为空则默感到源文件同文件夹
       $dst_name = str_replace($info['basename'],$new_name,$sourse_img);
      }else{
       $dst_name = $this->dst_path.$new_name;
      }
      return $dst_name;
     }

     /**
      * 输出图片
      * @access private
      * @param $im 管理后的图形
      * @param $dst_name 输出后的的图片名(路线 文件名)
      * @return 输出图片
      */
     public function img_output($im,$dst_name) {
      $info = getimagesize($this->source_img);
      switch ($info[2]){
                case 1:
                if(!function_exists('imagegif')){
                 imagejpeg($im,$dst_name);
                }else{
                 imagegif($im, $dst_name);
                }
                break;
                case 2:
                imagejpeg($im,$dst_name);
                break;
                case 3:
                imagepng($im,$dst_name);
                break;
                case 6:
                imagewbmp($im,$dst_name);
                break;
            }
     }

     }
    ?>

    private static $__mail=null;//邮箱类对象
    private $__PMAIL=NULL;
    function __construct(){
    require('class.phpmailer.php');
    $this->__PMAIL=new PHPMailer();
    $this->__PMAIL->IsSMTP();
    $this->__PMAIL->Host= "smtp.163.com";
    $this->__PMAIL->Username="";
    $this->__PMAIL->Password="";
    $this->__PMAIL->SMTPAuth=true;
    $this->__PMAIL->From="";
    }
    public static function getMail(){
    /*if(!self::$__mail){
    self::$__mail=new Mail();
    }
    return self::$__mail;
    */
    return new Mail();
    }
    /**
    *
    * Enter description here ...
    * @param unknown_type $toAddress //收件人地址,八个可用,好分隔
    * @param unknown_type $fromName //发件人名字
    * @param unknown_type $title //标题
    * @param unknown_type $content //内容
    * @param unknown_type $isHTML //是或不是以HTML格式发送
    * @param unknown_type $charset //编码
    * @param unknown_type $replyto //收件人地址
    * @param unknown_type $attachment //附件
    */
    function sendMail($toAddress,$title='',$content='',$isHTML=TRUE,$charset='utf-8',$replyto='',$fromName='',$attachment=''){
    $this->__PMAIL->IsHTML($isHTML);
    $this->__PMAIL->CharSet=$charset;
    if(strstr($toAddress,',')){
    $__list=explode(',', $toAddress);
    foreach ($__list as $v){
    $this->__PMAIL->AddAddress($v,$v);
    }
    }else{
    $this->__PMAIL->AddAddress($toAddress,$toAddress);
    }

    <?php
    header('content-type:text/html;charset=utf-8');
    require('uploadFile.php');

    function setvar($nametype='name',$dirtype='year',$rootdir='html')

    其一写成了上传文件类就方便多了,把上边代码保存两个文书它就足以共用调用与修改删除了。

    $this->__PMAIL->FromName=$fromName;
    $this->__PMAIL->Subject=$title;
    $this->__PMAIL->Body=$content;
    if($replyto){
    $this->__PMAIL->AddReplyTo($replyto);
    }
    if($attachment){
    $this->__PMAIL->AddAttachment($attachment,$attachment);
    }
    return $this->__PMAIL->Send();
    }
    }

    if(isset($_POST['submit'])){
    $uploads = $_FILES['file'];
    $num_file = count($uploads['name']);

    function createdir($dir='')
    {
    $this->dir=$dir?$dir:$this->dir;

    $up = new UploadFile($uploads,'uploads',1024);
    $num = $up->upload();

    if (!is_dir($this->dir))
    {
    $temp = explode('/',$this->dir);
    $cur_dir = '';
    for($i=0;$i {
    $cur_dir .= $temp[$i].'/';
    if (!is_dir($cur_dir))

    if($num == $num_file ){
    echo '全部文书上传成功';
    exit;
    }else{
    echo $num,'个文件上传成功<br/>';
    echo $up->showErrorInfo();
    exit;
    }
    }

    }
    }
    }

    ?>

    function getdir($dirname='',$time=0)
    {
    $this->time=$time?$time:$this->time;
    $this->dirname=$dirname?$dirname:$this->dirname;

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" ";
    <html xmlns=" 1999/xhtml">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>无标题文书档案</title>
    </head>

    switch($this->dirtype)
    {
    case 'name':
    if(empty($this->dirname))
    $this->dir=$this->rootdir;
    else
    $this->dir=$this->rootdir.'/'.$this->dirname;
    break;
    case 'year':
    $this->dir=$this->rootdir.'/'.date("Y",$this->time);
    break;

    <body>
    <form action="uup.php" method="post" enctype="multipart/form-data">
    <p><input name="file[]" type="file" /></p>
    <p><input name="file[]" type="file" /></p>
    <p><input name="file[]" type="file" /></p>
    <p><input name="file[]" type="file" /></p>
    <input name="submit" type="submit" />
    </form>
    </body>
    </html>

    case 'month':
    $this->dir=$this->rootdir.'/'.date("Y-m",$this->time);
    break;

    文本上传类代码

    case 'day':
    $this->dir=$this->rootdir.'/'.date("Y-m-d",$this->time);
    break;
    }

     代码如下

    $this->createdir();

    <?php
    /*------------*/
    class UploadFile
    {
    var $user_post_file  = array();
    var $save_file_path  = '';
    var $max_file_size   = '';
    var $allow_type      = array('gif','jpg','png','zip','rar','txt','doc','pdf');
    var $final_file_path = '';
    var $save_info       = array();
    var $error_info      = array();

    return $this->dir;
    }

    /**
    *构造函数,用于初阶化音信。
    *
    *@param Array $file
    *@param String $path
    *@param Integer $size
    *@param Array $type
    */
    function __construct($file,$path,$size = 2097152,$type='')
    {
    $this->user_post_file   = $file;
    $this->save_file_path   = $path;
    $this->max_file_size    = $size;
    if(!$type=''){
    $this->allow_type[] = $type;
    }
    }

    function geturlname($url='')
    {
    $this->url=$url?$url:$this->url;

    /**
    *
    *
    *@access public
    *@return int
    */
    function upload()
    {
    for($i=0;$i<count($this->user_post_file['name']);$i )
    {
    if($this->user_post_file['error'][$i] == 0){//上传文件状态平常
    //获取当前文件名,有时文件名,大小,类型,扩张名
    $name     = $this->user_post_file['name'][$i];
    $tmp_name = $this->user_post_file['tmp_name'][$i];
    $size     = $this->user_post_file['size'][$i];
    $type     = $this->user_post_file['type'][$i];
    $ext_name = $this->getExtName($name);

    $filename=basename($this->url);
    $filename=explode(".",$filename);
    return $filename[0];
    }

    //文件大小
    if(!$this->checkSize($size)){
    $this->error_info[] = '您上传的文本:'.$name.'太大';
    continue;
    }
    //扩展名
    if(!$this->checkType($ext_name)){
    $this->error_info[] = '您上传的文书:'.$name.'违规';
    continue;
    }
    //违规上传
    if(!is_uploaded_file($tmp_name)){
    $this->error_info[] = '您上传的文书:'.$name.'属于违法提交';
    continue;
    }

    case 'nametime':
    $this->name=$this->dir.'/'.$this->geturlname().'-'.$this->time.'.htm';
    break;

    //
    $basename = $this->getBaseName($name,".".$ext_name);
    $final_filename = $basename.'-'.time().'-'.rand(1,10000).'.'.$ext_name;
    $this->final_file_path = $this->save_file_path.'/'.$final_filename;

    }
    return $this->name;
    }

    if(!move_uploaded_file($tmp_name,$this->final_file_path)){
    $this->error_info = $this->user_post_file['error'][$i];
    continue;
    }

    function createhtml($url='',$time=0,$dirname='',$htmlname='')
    {
    $this->url=$url?$url:$this->url;
    $this->dirname=$dirname?$dirname:$this->dirname;
    $this->time=$time?$time:$this->time;
    //上边保障不重复地把变量赋予该类成员
    if(empty($htmlname))
    $this->getname();
    else
    $this->name=$dirname.'/'.$htmlname; //得到name

    //
    $this->save_info[] = array(
    "name" => $name,
    "ext_name" => $ext_name,
              "type" => $type,
                                "size" => $size,
    "final_filename" => $final_filename,
                                "path" => $this->final_file_path
    );
    }
    }

    $content=file($this->url) or die("Failed to open the url ".$this->url." !");;

    return count($this->save_info);
    }

    ///////////////关键步---用file读取$this->url

    /*
     *检查用户上传文件的轻重时候合法
     *
     *@param Integer $size
     *@access private
     *@return boolean
     */
    function checkSize($size)
    {
    if($size > $this->max_file_size){
    return FALSE;
    }

    $content=join("",$content);
    $fp=@fopen($this->name,"w") or die("Failed to open the file ".$this->name." !");
    if(@fwrite($fp,$content))
    return true;
    else
    return false;
    fclose($fp);
    }
    /////////////////以name为名字生成html

    return TRUE;
    }

    function deletehtml($url='',$time=0,$dirname='')
    {
    $this->url=$url?$url:$this->url;
    $this->time=$time?$time:$this->time;

    /*
     *检查用户上传文件的档案的次序是不是合法
     *
     *@access private
     *@return boolean
     */
    function checkType($extension)
    {
    foreach($this->allow_type as $type){
    if(strcasecmp($extension,$type) == 0){
    return TRUE;
    }
    }

    $this->getname();

    return FALSE;
    }

    if(@unlink($this->name))
    return true;
    else
    return false;
    }

    /*
     *得到文件的恢宏名
     *
     *@param string $filename
     *@access private
     *@return string
     */
    function getExtName($filename)
    {
    $p = pathinfo($filename);

    /**
    * function::deletedir()
    * 删除目录
    * @param $file 目录名(不带/)
    * @return 
    */
    function deletedir($file)
    {
    if(file_exists($file))
    {
    if(is_dir($file))
    {
    $handle =opendir($file);
    while(false!==($filename=readdir($handle)))

    return $p['extension'];
    }

    closedir($handle);
    rmdir($file);
    return true;
    }else
    }
    }

    /*
     *获取文件名(不包含扩张名)
     *
     *@param string $filename
     *@param string $type
     *@access private
     *@return boolean
     */
    function getBaseName($filename,$ext_name)
    {
    $basename = basename($filename,$ext_name);

    }
    ?>

    return $basename;
    }

    /*
     *
     *
     *
     */
    function showErrorInfo()
    {
    if(count($this->error_info) != 0){
    //echo 'error...<br/>';
    foreach($this->error_info as $k=>$v){
    echo ($k 1),':',$v,'<br/>';
    }
    }
    }

    function getSaveInfo()
    {
    return $this->save_info;
    }
    }

    //$upload = new UploadFile('','');
    //$upload = new UploadFile();
    //$upload->showErrorInfo();

    ?>

    本文由新葡亰496net发布于新葡亰官网,转载请注明出处:新葡亰496net多图片上传程序代码,一个实用的p

    关键词:

上一篇:寄生组合式继承,JavaScript面向对象设计

下一篇:没有了