如何使用php脚本给html中引用的js和css路径打上版本号


Posted in PHP onNovember 18, 2015

在搜索引擎中搜索关键字.htaccess 缓存,你可以搜索到很多关于设置网站文件缓存的教程,通过设置可以将css、js等不太经常更新的文件缓存在浏览器端,这样访客每次访问你的网站的时候,浏览器就可以从浏览器的缓存中获取css、js等,而不必从你的服务器读取,这样在一定程度上加快了网站的打开速度,又可以节约一下你的服务器流量。

具体文字说明不给大家多说了,下面通过代码实例给大家讲解。

比如

<link rel="stylesheet" type="text/css" href="./css/globel.css">
<script src="./js/config.js"></script>

中的href和src加上版本

<link rel="stylesheet" type="text/css" href="./css/globel.css?eslc-app=3-0-2">
<script src="./js/config.js?eslc-app=3-0-2"></script>

当然如果不是前后端 分离得干干净净的,就没必要这么额外的这样自己在写个脚本去打版本。

打版本的好处:

解决外部引用文件实时更新问题。比如

pc端上主要体现在 iframe中的外部引用文件不会实时更新。

wap端上部分app也是比如微信。 如果你的网页是嵌到自己的app,那也更不用说了。

用php写了个类

//生成版本
//清除版本
class ReplaceVersion{
 protected $filePostFixs = array();
 protected $versionName = null;
 protected $version = null;
 protected $path = null;
 /**
  * @param mixed $configs 
  * @param [type] $profix [description]
  * @param [type] $path  [description]
  */
 public function __construct($configs, $profix, $path){
  if (!$this->isCanRun()) {
   $this->error('必须在内网环境 10.10.0开头才可运行'); //exit;
  }
  $this->setVersion($configs);
  $this->setFilePostFix($profix);
  $this->path = $path;
 }
 protected function isCanRun(){
  if (strpos($_SERVER['HTTP_HOST'], '10.10.0') !== false) {
   return true;
  }
  return false;
 }
 /**
  * 匹配到script节点
  * @param array $match 匹配到的script
  * @return string 处理好的script
  */
 protected function callbackScript($match){
  //["<script src="../js/config.js?is=new"></script>", "../js/config.js", "?is=new"]
  /*/<script.*?src=\"(.*?)(\?.*?|\?)?\".*?><\/script>/*/
  $str = $match[0];
  $pattern = '/(<script.*?src=\")(.*)?(\"><\/script>)/';
  return $this->callbackMatch($str, $pattern);
 }
 /**
  * 匹配到css节点
  * @param array $match 匹配到的css
  * @return string 处理好的css
  */
 protected function callbackCss($match){
  // '<link rel="stylesheet" type="text/css" href="../css/globel.css">';
  $str = $match[0];
  $pattern = '/(<link.*?href=\")(.*)?(\".*?>)/';
  return $this->callbackMatch($str, $pattern);
 }
 /**
  * 回调模式匹配
  * @param string $str 
  * @param string $pattern
  * @return string  
  */
 protected function callbackMatch($str, $pattern){
  switch ($this->dealFlag) {
   case 'replace':
    return $this->replaceCallbackMatch($str, $pattern);
   case 'clean':
    return $this->cleanCallbackMatch($str, $pattern);
   default:
    $this->error('非法模式');
  }
 }
 /**
  * 替换版本
  * @param string $str 待处理的string
  * @param string $pattern 正则
  * @return string  处理后的string
  */
 protected function replaceCallbackMatch($str, $pattern){
  if (!preg_match($pattern, $str, $third)) {
   return $str;
  }
  $arr  = explode('?', $third[2]);
  $len  = count($arr);
  $versionName = $this->versionName;
  $version = $this->version;
  if ($len === 1) {//没有问号
   $arr[0] .= '?'. $versionName. '='. $version;
  }else{//有问号
   if (preg_match('/(^|\&)'. $versionName.'=(.*?)($|\&)/', $arr[1])) {//存在
    $arr[1] = preg_replace('/(^|\&)'. $versionName.'=(.*?)($|\&)/', '$1'. $versionName.'='. $version. '$3', $arr[1]);
    $arr[0] .= '?'. $arr[1];
   }else{//不存在
    $arr[0] .= '?'. $arr[1]. '&'. $versionName. '='. $version;
   }
  }
  return $third[1]. $arr[0]. $third[3];
 }
 /**
  * 清除版本
  * @param string $str 待清除的版本
  * @param string $pattern 正则
  * @return string  清除后的string
  */
 protected function cleanCallbackMatch($str, $pattern){
  if (!preg_match($pattern, $str, $third)) {
   return $str;
  }
  $arr  = explode('?', $third[2]);
  $len  = count($arr);
  $versionName = $this->versionName;
  if ($len > 1 && strpos($arr[1], $versionName. '=') !== false) {
   $arr[1] = preg_replace('/(^|\&)'. $versionName.'=(.*?)($|\&)/', '$1', $arr[1]);
   substr($arr[1], -1) === '&' && ($arr[1] = substr($arr[1], 0, -1));
   $arr[0] .= strlen($arr[1]) > 0 ? '?'. $arr[1] : '';
   $str = $third[1]. $arr[0]. $third[3];
  }
  return $str;
 }
 /**
  * 执行
  */
 protected function run(){
  if ($this->path == '') {
   $this->error('empty path');
   return ;
  }
  if (is_dir($this->path)) {
   $this->setDirFilesVersion( $this->path );
  }else if(is_file($this->path)){
   $this->setFileVersion( $this->path );
  }else{
   $this->error('error path');
  }
 }
 /**
  * 添加版本
  */
 public function replace(){
  $this->dealFlag = 'replace';
  $this->run();
  echo 'replace success';
 }
 /**
  * 清除版本
  */
 public function clean(){
  $this->dealFlag = 'clean';
  $this->run();
  echo 'clean success';
 }
 protected function success(){
 }
 protected function error($errorMsg){
  echo $errorMsg;
  exit();
 }
 protected function setDirFilesVersion($dir){
  $handle = null;
  $file  = null;
  if ( $handle = opendir($dir)) {
   while ( false !== ($file = readdir($handle)) ) {
    if ($file === '.' || $file === '..' || strpos($file, '.') === -1 ) {continue;}
    $this->setFileVersion($file);
   }
  }
 }
 protected function setFileVersion($file){
  $temp = null;
  /*$pattern = '/<script.*?src=\"(.*?)(\?.*?|\?)?\".*?><\/script>/';*/
  $temp = explode('.', $file) ;
  if ( ! $this->isNeedReplacePostFix(array_pop( $temp )) ) {return;}
  $content = null;
  $content = file_get_contents($file);
  $content = preg_replace_callback('/<script.*?><\/script>/', array(&$this, 'callbackScript'), $content);
  $content = preg_replace_callback('/<link.*?type="text\/css".*?>/', array(&$this, 'callbackCss'), $content);
  // highlight_string($content);
  file_put_contents($file, $content);
 }
 /**
  * 获得版本
  * @param mixed $configs array( 'versionName' : 'version') || $versionName
  */
 protected function setVersion($configs){
  // last_wap_version  = '3-0-0', 
  // wap_version = '3-0-1',
  if (is_array($configs) && $configs > 0) {
   foreach ($configs as $key => $value) {
    $this->version = $value;
    $this->versionName = $key;
   }
  }else if(is_string($configs) && $configs != ''){
   $configs = explode(',', $configs);
   $this->versionName = $configs[0];
   count($configs) == 2 && ($this->version = $configs[1]);
  }else{
   $this->error('the version is empty');
  }
 }
 /**
  * 通过后缀判断该文件是否要添加或清除版本
  * @param string $profix 后缀
  * @return boolean  true | false
  */
 protected function isNeedReplacePostFix($profix){
  if (in_array($profix, $this->filePostFixs)) {
   return true;
  }
  return false;
 }
 /**
  * 设置需要操作的后缀
  */
 public function setFilePostFix($profix){
  if (is_array($profix)) {
   count($profix) > 0 && ( $this->filePostFixs = array_merge($this->filePostFixs, $profix) );
  }else if(is_string($profix)){
   $this->filePostFixs[] = $profix;
  }
 }
}

使用:

$dir  = __DIR__;
$is_clean = false;
//$is_clean = true;
//第一个参就是版本信息, 第二个就是要匹配的文件后缀, 第三个是要匹配的目录或者文件
if ($is_clean) {//清除版本
 $configs = 'eslc-wap';
 $replaceObj = new ReplaceVersion($configs, array('html'), $dir);
 $replaceObj->clean();
}else{//添加或替换版本
 $configs = array('eslc-wap' => '1.0.1');//也可以写成 $configs = 'eslc-wap, 1.0.1';
 $replaceObj = new ReplaceVersion($configs, array('html'), $dir);
 $replaceObj->replace();
}
PHP 相关文章推荐
PHP新手上路(八)
Oct 09 PHP
php access 数据连接与读取保存编辑数据的实现代码
May 12 PHP
深入解析php之apc
May 15 PHP
CodeIgniter输出中文乱码的两种解决办法
Jun 12 PHP
用PHP解决的一个栈的面试题
Jul 02 PHP
PHP中echo和print的区别
Aug 28 PHP
php 指定范围内多个随机数代码实例
Jul 18 PHP
深入浅析Yii admin的权限控制
Aug 31 PHP
php表单文件iframe异步上传实例讲解
Jul 26 PHP
php5.x禁用eval的操作方法
Oct 19 PHP
thinkphp5.1框架实现格式化mysql时间戳为日期的方式小结
Oct 10 PHP
laravel model模型定义实现开启自动管理时间created_at,updated_at
Oct 17 PHP
php生成唯一数字id的方法汇总
Nov 18 #PHP
基于PHP给大家讲解防刷票的一些技巧
Nov 18 #PHP
使用PHP uniqid函数生成唯一ID
Nov 18 #PHP
使用PHP实现生成HTML静态页面
Nov 18 #PHP
php+ajax无刷新上传图片实例代码
Nov 17 #PHP
php计算年龄精准到年月日
Nov 17 #PHP
php实现简单的上传进度条
Nov 17 #PHP
You might like
部署PHP项目应该注意的几点事项分享
2013/12/20 PHP
php文件读取方法实例分析
2015/06/20 PHP
配置eAccelerator和XCache扩展来加速PHP程序的执行
2015/12/22 PHP
PHP实现的观察者模式实例
2017/06/21 PHP
PHP设计模式(三)建造者模式Builder实例详解【创建型】
2020/05/02 PHP
11款基于Javascript的文件管理器
2009/10/25 Javascript
Web开发者必备的12款超赞jQuery插件
2010/12/03 Javascript
jQuery过滤选择器:not()方法使用介绍
2014/04/20 Javascript
js使用for循环查询数组中是否存在某个值
2014/08/12 Javascript
基于jQuery实现的文字按钮表单特效整理
2014/12/07 Javascript
javascript实现获取字符串hash值
2015/05/10 Javascript
jQuery实现带玻璃流光质感的手风琴特效
2015/11/20 Javascript
jQuery mobile类库使用时加载导航历史的方法简介
2015/12/04 Javascript
JQuery学习总结【二】
2016/12/01 Javascript
基于javascript实现的购物商城商品倒计时实例
2016/12/11 Javascript
jquery广告无缝轮播实例
2017/01/05 Javascript
vue中手机号,邮箱正则验证以及60s发送验证码的实例
2018/03/16 Javascript
详解Vue中watch对象内属性的方法
2019/02/01 Javascript
iview form清除校验状态的实现
2019/09/19 Javascript
layui 上传文件_批量导入数据UI的方法
2019/09/23 Javascript
ES2020系列之空值合并运算符 '??'
2020/07/22 Javascript
Python编程中的文件读写及相关的文件对象方法讲解
2016/01/19 Python
查看Django和flask版本的方法
2018/05/14 Python
python 删除字符串中连续多个空格并保留一个的方法
2018/12/22 Python
基于Python对数据shape的常见操作详解
2018/12/25 Python
python破解bilibili滑动验证码登录功能
2019/09/11 Python
浅谈keras中Dropout在预测过程中是否仍要起作用
2020/07/09 Python
TripAdvisor越南:全球领先的旅游网站
2017/09/21 全球购物
婴儿鞋,独特的婴儿服装和配件:Zutano
2018/11/03 全球购物
Nike意大利官网:Nike.com IT
2020/01/19 全球购物
周年庆典邀请函范文
2014/01/24 职场文书
cf收人广告词大全
2014/03/14 职场文书
2015年公司国庆放假通知
2015/07/30 职场文书
幼儿园大班教师随笔
2015/08/14 职场文书
《实心球》教学反思
2016/02/23 职场文书
PHP 技巧 * SVG 保存为图片(分享图生成)
2021/04/02 PHP