PHP日志压缩下载
主要实现了在后台查看日志列表及打包下载功能。

由于用到了PHP压缩功能,特此记录下。
压缩下载类:
Hzip.php
<?php
/**
* Created by PhpStorm.
* @author: YJC
* @date: 2017/1/4
*/
namespace Yjc;
use ZipArchive;
class Hzip
{
/**
* Add files and sub-directories in a folder to zip file.
* @param string $folder
* @param ZipArchive $zipFile
* @param int $exclusiveLength Number of text to be exclusived from the file path.
*/
private static function folderToZip($folder, &$zipFile, $exclusiveLength) {
$handle = opendir($folder);
while (false !== $f = readdir($handle)) {
if ($f != '.' && $f != '..') {
$filePath = "$folder/$f";
// Remove prefix from file path before add to zip.
$localPath = substr($filePath, $exclusiveLength);
if (is_file($filePath)) {
$zipFile->addFile($filePath, $localPath);
} elseif (is_dir($filePath)) {
// Add sub-directory.
$zipFile->addEmptyDir($localPath);
self::folderToZip($filePath, $zipFile, $exclusiveLength);
}
}
}
closedir($handle);
}
private static function fileToZip($folder, &$zipFile, $exclusiveLength) {
$localPath = substr($folder, $exclusiveLength);
$zipFile->addFile($folder, $localPath);
}
/**
* Zip a folder (include itself).
* Usage:
* HZip::zipDir('/path/to/sourceDir', '/path/to/out.zip');
*
* @param string $sourcePath Path of directory to be zip.
* @param string $outZipPath Path of output zip file.
*/
public static function zipDir($sourcePath, $outZipPath)
{
$pathInfo = pathinfo($sourcePath);
$parentPath = $pathInfo['dirname'];
$dirName = $pathInfo['basename'];
$z = new ZipArchive();
$z->open($outZipPath, ZipArchive::CREATE);
$z->addEmptyDir($dirName);
if(is_dir($sourcePath)){
self::folderToZip($sourcePath, $z, strlen("$parentPath/"));
}else{
self::fileToZip($sourcePath, $z, strlen("$parentPath/"));
}
$z->close();
}
public static function download($file){
// $filename = sys_get_temp_dir() ."/log.zip"; //最终生成的文件名(含路径)
$filename = sys_get_temp_dir() ."/". basename($file) . '.zip'; //最终生成的文件名(含路径)
self::zipDir($file, $filename);
// header("Cache-Control: public");
// header("Content-Description: File Transfer");
// header("Content-type: application/octet-stream ");
// header("Accept-Ranges: bytes ");
header('Content-disposition: attachment; filename='.basename($filename)); //文件名
header("Content-Type: application/zip"); //zip格式的
header("Content-Transfer-Encoding: binary"); //告诉浏览器,这是二进制文件
header('Content-Length: '. filesize($filename)); //告诉浏览器,文件大小
ob_clean();
flush();
@readfile($filename);
}
/**
* 转换文件大小
* @param $fileSize
* @return string
*/
public static function convertSize($fileSize) {
$size = sprintf("%u", $fileSize);
if($size == 0) {
return("0 Bytes");
}
$sizename = array(" Bytes", " KB", " MB", " GB", " TB", " PB", " EB", " ZB", " YB");
return round($size/pow(1024, ($i = floor(log($size, 1024)))), 2) . $sizename[$i];
}
/**
* 获取文件夹大小
* 不建议使用,太慢
* @param $dir
* @return int
*/
public static function getDirSize($dir)
{
//避免计算父级目录
if(stripos($dir, '..')){
return filesize($dir);
}
$sizeResult = 0;
$handle = opendir($dir);
while (false!==($FolderOrFile = readdir($handle)))
{
if($FolderOrFile != "." && $FolderOrFile != "..")
{
if(is_dir("$dir/$FolderOrFile")){
$sizeResult += self::getDirSize("$dir/$FolderOrFile");
}else{
$sizeResult += filesize("$dir/$FolderOrFile");
}
}
}
closedir($handle);
return $sizeResult;
}
}
?>
逻辑部分无非就是打开某个目录,然后列出来:
/**
* 日志管理
*/
public function LogsList(){
//默认路径
$default_dir = APP_PATH . "Logs/";
//获取路径
if(isset($_GET['path'])){
$dirpath = $_GET['path'];
}else{
$dirpath = $default_dir;
}
//路径安全检查
if(stripos($dirpath, 'Logs') === false){
$dirpath = $default_dir;
}
//规范化路径
$dirpath = realpath($dirpath);
//操作
$op = empty($_GET['op']) ? 'list' : $_GET['op'];
switch ($op){
case 'list':
$this->LogsListList($dirpath);
break;
case 'download':
\Yjc\Hzip::download($dirpath);
break;
}
}
private function LogsListList($dirpath){
//打开路径
$d = dir($dirpath);
$data = array();
$data['path'] = $d -> path;
// $data['log_path'] = getDomain() . "/Logs/http/$date";
while ( false !== ( $entry = $d -> read ())) {
// $entryname = realpath($d -> path .'/'. $entry);
$entryname = $d -> path .'/'. $entry;
// $filesize = \Yjc\Hzip::getDirSize($entryname);
$filesize = filesize($entryname);
$files = array(
'path' => $d->path,
'name' => $entry,
'entry' => $entryname,
'size' => \Yjc\Hzip::convertSize($filesize),//大小
'mtime' => filemtime ($entryname),
'type' => is_dir($entryname) ? 'dir' : 'file',
'can_down' => in_array($entry, array('.', '..')) ? 0 : 1,
);
$filenames[] = $entry;
$data['entrys'][] = $files;
}
//排序
array_multisort($filenames,SORT_ASC,SORT_STRING, $data['entrys']);
$d -> close ();
// dump($data);
$this->assign('data', $data);
$this->display(':http_logs_list');
}
前端把$data展示出来就行啦:
<table class="table table-striped table-bordered table-hover dataTable no-footer" role="grid" aria-describedby="sample_1_info">
<thead>
<tr role="row">
<th width="13%">文件名</th>
<th width="7%">大小</th>
<th width="7%">类型</th>
<th width="13%">更新时间</th>
<th width="6%">操作</th>
</tr>
</thead>
<tbody>
<volist name="data.entrys" id="vo">
<tr class="gradeX odd" role="row">
<td>
<eq name="vo.type" value="dir">
<a href="{:U('Logstats/LogsList')}?path={$vo.entry}">{$vo.name} <i class="fa"></i></a>
<else/>
{$vo.name}
</eq>
</td>
<td>{$vo.size}</td>
<td>{$vo.type}</td>
<td>{$vo.mtime|date='Y-m-d H:i:s' , ###}</td>
<td>
<eq name="vo.can_down" value="1">
<a href="{:U('Logstats/LogsList')}?op=download&path={$vo.entry}" target="_blank" class="btn btn-xs green">下载 <i class="fa"></i></a>
<else/>
</eq>
</td>
</tr>
</volist>
</tbody>
</table>
参考:
1、php如何读取文件夹目录里的文件并按照日期,大小,名称排序 - fzxu_05的个人页面
https://my.oschina.net/wojibuzhu/blog/211674
2、php 文件下载 出现下载文件内容乱码损坏的解决方法 - 微凉 - 博客频道 - CSDN.NET
http://blog.csdn.net/wlqf366/article/details/8744599
3、php实现在线解压、压缩zip文件并下载 | 常亮的技术博客
http://www.diantuo.net/328
PHP日志压缩下载的更多相关文章
- Sqlserver2008日志压缩
SqlServer2008日志压缩语句如下: USE [master] GO ALTER DATABASE DBName SET RECOVERY SIMPLE WITH NO_WAIT GO ALT ...
- 我是如何利用Hadoop做大规模日志压缩的
背景 刚毕业那几年有幸进入了当时非常热门的某社交网站,在数据平台部从事大数据开发相关的工作.从日志收集.存储.数据仓库建设.数据统计.数据展示都接触了一遍,比较早的赶上了大数据热这波浪潮.虽然今天的人 ...
- Java批量压缩下载
最近做了一些有关批量压缩下载的功能,网上也找了一些资源,但都不是太全面,所以自己整理一份,已备不时之需. 直接上代码: // 获取项目路径 private static String WEBCLASS ...
- Shell + crontab 实现日志压缩归档
Shell + crontab 实现日志压缩归档 crontab # archive the ats log days. */ * * * * root /bin/>& shell #! ...
- linux下的日志压缩脚本
linux下的日志压缩脚本: #!/bin/bash #第一步:先定义项目列表如下: projects="project-a project-b project-c project-d&qu ...
- Kafka日志压缩剖析
1.概述 最近有些同学在学习Kafka时,问到Kafka的日志压缩(Log Compaction)问题,对于Kafka的日志压缩有些疑惑,今天笔者就为大家来剖析一下Kafka的日志压缩的相关内容. 2 ...
- 用Spring中的ResponseEntity文件批量压缩下载
我看了很多网上的demo,先生成ZIP压缩文件,然后再下载. 我这里是生成ZIP文件流 进行下载.(核心代码没多少,就是一些业务代码) @RequestMapping(value = "/& ...
- JAVA 实现将多目录多层级文件打成ZIP包后保留层级目录下载 ZIP压缩 下载
将文件夹保留目录打包为 ZIP 压缩包并下载 上周做了一个需求,要求将数据库保存的 html 界面取出后将服务器下的css和js文件一起打包压缩为ZIP文件,返回给前台:在数据库中保存的是html标签 ...
- MIT 6.824 Lab2D Raft之日志压缩
书接上文Raft Part C | MIT 6.824 Lab2C Persistence. 实验准备 实验代码:git://g.csail.mit.edu/6.824-golabs-2021/src ...
随机推荐
- Angular2入门系列教程2-项目初体验-编写自己的第一个组件
上一篇 使用Angular-cli搭建Angular2开发环境 Angular2采用组件的编写模式,或者说,Angular2必须使用组件编写,没有组件,你甚至不能将Angular2项目启动起来 紧接着 ...
- ASP.NET路由模型解析
大家好,我又来吹牛逼了 ~-_-~ 转载请注明出处:来自吹牛逼之<ASP.NET路由模型解析> 背景:很多人知道Asp.Net中路由怎么用的,却不知道路由模型内部的运行原理,今天我就给大家 ...
- [C#] 简单的 Helper 封装 -- CookieHelper
using System; using System.Web; namespace ConsoleApplication5 { /// <summary> /// Cookie 助手 // ...
- 【Machine Learning】机器学习及其基础概念简介
机器学习及其基础概念简介 作者:白宁超 2016年12月23日21:24:51 摘要:随着机器学习和深度学习的热潮,各种图书层出不穷.然而多数是基础理论知识介绍,缺乏实现的深入理解.本系列文章是作者结 ...
- Web安全相关(三):开放重定向(Open Redirection)
简介 那些通过请求(如查询字符串和表单数据)指定重定向URL的Web程序可能会被篡改,而把用户重定向到外部的恶意URL.这种篡改就被称为开发重定向攻击. 场景分析 假设有一个正规网站http:// ...
- vscode 1.5安装体验
1.下载安装 官方下载地址: http://code.visualstudio.com/ 界面截图: 2.图标显示功能File Icon Themes vscode1.5版本文件夹视图,可显示文件类型 ...
- WebApi返回Json格式字符串
WebApi返回json格式字符串, 在网上能找到好几种方法, 其中有三种普遍的方法, 但是感觉都不怎么好. 先贴一下, 网上给的常用方法吧. 方法一:(改配置法) 找到Global.asax文件,在 ...
- the Zen of Python---转载版
摘自译文学习区 http://article.yeeyan.org/view/legendsland/154430 The Zen of Python Python 之禅 Beautiful is b ...
- 如何查看w3p.exe 和IIS 应用程序池的关系
图形界面方式 命令行方式 如果找不到 appcmd Appcmd.exe exists at the location %systemroot%\system32\inetsrv\. You eith ...
- [每日Linux]Linux下xsell和xftp的使用
实验缘由: 1.xsell在Linux下的作用就是远程登录的一个界面,也就是实现访问在Windows下访问Linux服务器的功能.之前在数据挖掘实验中因为自己电脑的内存不够,曾经使用过实验室的服务器跑 ...