php读取大文件示例分享(文件操作类)_PHP
Lib_File2.php
复制代码 代码如下:
class Lib_File2
{
//文件目录
private $root = '/data/wwwroot/kkpromo/data/';
//文件后缀
private $suffix = '.log';
//文件句柄
private $handle=null;
//一次读取文件的最大记录数
private $limit=40000;
//每行读取的字节长度
private $length=1024;
//开始时间
private $startTime=0;
//内存使用基准点
private static $startMemory=0;
//
private $conn=null;
//
private static $init=null;
public static function instance()
{
self::$startMemory = memory_get_usage(true);
if(self::$init && is_object(self::$init))
{
return self::$init;
}
self::$init = new self();
return self::$init;
}
private function __construct(){}
public function setRoot($root)
{
if(!is_dir($root)) die($root.' ROOT DOES NOT EXIST');
$this->root = $root;
}
public function setSuffix($suffix)
{
$this->suffix = $suffix;
}
public function setLimit($limit)
{
if(!is_numeric($limit)) die($limit.' SHOULD BE NUMBERIC');
if(intval($limit) > 1000000) die($limit.' SHOULD BE LOWER THAN 1000000');
$this->limit = intval($limit);
}
public function _getFile($date , $appid , $op)
{
$filename = rtrim($this->root , '/').DIRECTORY_SEPARATOR.$date.DIRECTORY_SEPARATOR.$appid.'.'.$op.$this->suffix;
if(!file_exists($filename))
{
die($filename.' FILE DOES NOT EXISTS!');
}
if(!is_file($filename))
{
die($filename.' FILE DOES NOT EXIST!');
}
if(!is_readable($filename))
{
die($filename.' FILE ACCESS DENY!');
}
return $filename;
}
public function closeFile($date=null , $appid=null , $op=null)
{
if($op && $date && $appid)
{
if(is_object($this->handle[$date.'_'.$appid.'_'.$op]) || $this->conn[$date.'_'.$appid.'_'.$op])
{
unset($this->handle[$date.'_'.$appid.'_'.$op]);
$this->handle[$date.'_'.$appid.'_'.$op]=null;
}
$this->conn[$date.'_'.$appid.'_'.$op]=null;
$this->handle[$date.'_'.$appid.'_'.$op]=null;
unset($this->handle[$date.'_'.$appid.'_'.$op]);
}
else {
if(is_array($this->handle) && $this->handle)
{
foreach ($this->handle as $key=>$val){
unset($this->handle[$key]);
$this->conn[$key]=null;
$this->handle[$key]=null;
}
}
}
return true;
}
private function _openFile($date , $appid , $op)
{
$this->startTime = microtime(true);
if(isset($this->conn[$date.'_'.$appid.'_'.$op]) && $this->conn[$date.'_'.$appid.'_'.$op])
{
return $this->handle[$date.'_'.$appid.'_'.$op];
}
$filename = self::_getFile($date , $appid , $op);
if(($this->handle[$date.'_'.$appid.'_'.$op] = new SplFileObject($filename , 'r'))!=null)
{
$this->conn[$date.'_'.$appid.'_'.$op] = true;
return $this->handle[$date.'_'.$appid.'_'.$op];
}
else {
die('FILE OPEN FAILED!');
}
}
/**
* 功能:解析数据
* 格式: array('timestamp','mid','data');
* @param string $data
* @return boolean|array
*/
private function _parseData($data , $jsonFlag=true)
{
if(empty($data) || !is_string($data)) return false;
$result = array(
'timestamp'=>0,
'mid'=>0,
'data'=>array(),
);
$data = explode('|', $data);
if(count($data) $result['timestamp'] = $data[0];
$result['mid'] = $data[1];
if($jsonFlag)
{
$result['data'] = @json_decode($data[2] , true);
unset($result['mid']);
}
if(empty($result['timestamp']) || empty($result['mid'])) return false;
unset($data);
return $result;
}
/**
* TODO:读取单一文件
* @param string $date: 如(20140327)
* @param int $appid: 如(1000,9000)
* @param string $op:如(show,login , index)
* @param number $startNum 默认从第一行开始
* @param number $length 默认到$this->limit 读取的行数
* @param array $condition:array('mid'=>arrray() , 'ip'=>array() , ...) 过滤条件
* @param bool $jsonFlag:默认为true, 则保留jsondata字段;设为false,则去掉false字段
* @return array(count , diffTime , memory , data)
*/
public function readFile($date , $appid , $op , $startNum=0 , $length=0 , $jsonFlag=false , $condition=array())
{
$data['data'] = "";
$data['count'] = 0;
$index = $startNum;
$startNum = empty($startNum) ? 0 : $startNum;
$length = empty($length) ? $this->limit : $length;
$handle = self::_openFile($date , $appid , $op );
$line_number=0;
if($handle)
{
$handle->seek($startNum);
$handle->setMaxLineLen($this->length);
while (intval($line_number) - intval($startNum) {
$tmp = $handle->current();
if(empty($tmp)) continue;
$tmp = self::_parseData($tmp , $jsonFlag);
$line_number = $handle->key();
!$jsonFlag && $condition= array();
if(isset($condition) && $condition)
{
$key = array_keys($condition);
if(in_array($tmp['data'][$key[0]], $condition[$key[0]]))
{
$data['count']++;
$data['data'][$line_number] = $tmp;
}
}
else
{
$data['data'][$line_number] = $tmp;
$data['count']++;
}
if(intval($line_number) - intval($startNum) >= intval($length)-1) break;
unset($tmp);
$handle->next();
}
unset($tmp , $length , $line_number , $condition);
}
$data['diffTime'] = doubleval(microtime(true)) - doubleval($this->startTime);
$data['memory'] = doubleval((doubleval(memory_get_usage(true)) - doubleval(self::$startMemory))/1024/1024) . ' M';
return $data;
}
/**
* TODO:命令行下获取文件总记录数*
* @param string $date
* @param int $appid
* @param string $op
* @return array
*/
public function total_lineFile($date, $appid, $op)
{
$this->_openFile($date, $appid, $op);
$file = escapeshellarg($this->_getFile($date, $appid, $op)); // 对命令行参数进行安全转义
$line = `wc -l $file`;
if(preg_match("/(\d{1,})/", $line , $ret)){
$data['count']=$ret[1];
}else{
$data['count']=0;
}
$data['diffTime'] = doubleval(microtime(true)) - doubleval($this->startTime);
$data['memory'] = doubleval((doubleval(memory_get_usage(true)) - doubleval(self::$startMemory))/1024/1024) . ' M';
return $data;
}
/**
* TODO:统计{$data}.{$op}.log记录数
* @param string $date
* @param int $appid
* @param string $op
* @param array $condition
* @return array
*/
public function countFile($date , $appid , $op ,$condition=array())
{
$data['count'] = 0;
$handle = self::_openFile($date , $appid , $op );
if($handle)
{
$handle->setMaxLineLen($this->length);
while (!$handle->eof())
{
$tmp = $handle->current();
if(empty($tmp)) continue;
$tmp = self::_parseData($tmp);
if($condition && is_array($condition) )
{
$key = array_keys($condition);
if(isset($tmp['data'][$key[0]]) && $tmp['data'][$key[0]] && in_array($tmp['data'][$key[0]], $condition[$key[0]]))
{
$data['count']++;
}
}
else
{
$data['count']++;
}
unset($tmp);
$handle->next();
}
}
unset($handle , $condition , $tmp , $key , $val);
self::closeFile($date , $appid , $op );
$data['diffTime'] = doubleval(microtime(true)) - doubleval($this->startTime);
$data['memory'] = doubleval((doubleval(memory_get_usage(true)) - doubleval(self::$startMemory))/1024/1024) . ' M';
return $data;
}
/**
* TODO:统计用户数
* @param string $date
* @param int $appid
* @param string $op
* @param bool $midflag :默认为false 则 mid返回空数组;如设为true,则mid数组不为空
* * @param bool $jsonFlag:默认为true, 则保留jsondata字段;设为false,则去掉jsondata字段
* @param array $condition
* @return : array:形如({"mid":[],"count":2181,"diffTime":0.0397667884827,"memory":"3.75 M"})
*/
public function countFileMID($date , $appid , $op , $midflag=false , $jsonFlag=false, $condition=array())
{
//$count = self::total_lineFile($date , $appid , $op );
$count = self::countFile($date , $appid , $op );
$index = ceil($count['count'] / $this->limit);
$result = array('mid'=>array() , 'count'=>0 , 'diffTime'=>0 , 'memory'=>0);
for ($i=0 ; $i {
$startNum = $this->limit*$i;
$endNum = $this->limit;
$data = self::readFile($date , $appid , $op , $startNum , $endNum , $jsonFlag);
var_dump($data);exit();
if($data['data'] && is_array($data['data']))
{
foreach ($data['data'] as $arr)
{
if($condition && is_array($condition))
{
$key = array_keys($condition);
if(isset($arr['data'][$key[0]]) && (in_array($arr['data'][$key[0]] , $condition[$key]) || empty($condition[$key[0]])))
{
$result['mid'][$arr["mid"]] =1;
$result['count']++;
}
}
else
{
$result['mid'][$arr["mid"]] =1;
$result['count']++;
}
unset($data);
}
}
}
unset($index , $count , $condition , $data , $arr);
self::closeFile($date , $appid , $op);
$result['mid'] = array_keys($result['mid']);
if(empty($midflag)) unset($result['mid']);
$result['diffTime'] = doubleval(microtime(true)) - doubleval($this->startTime);
$result['memory'] = (memory_get_usage(true) - self::$startMemory)/1024/1024 . ' M';
return $result;
}
/**
* TODO:跨时间段 统计参加$op用户数据
* @param string $date
* @param int $appid
* @param string $op
* @param number $day
* @param bool $midflag :默认为false 则 mid返回空数组;如设为true,则mid数组不为空
* @return array 形如("20140326":{"mid":[],"count":4571,"diffTime":0.0806441307068,"memory":"3.75 M"},
* "20140325":{"mid":[],"count":2181,"diffTime":0.0397667884827,"memory":"3.75 M"})
*/
public function getReturnUser($date , $appid , $op , $day=1 , $midflag=false)
{
$date_i=0;
for ($i =0; $i $date_i = date('Ymd' , strtotime($date)-$i*86400);
$result[$date_i] = self::countFileMID($date_i , $appid , $op , $midflag);
}
unset($date , $date_i , $appid , $op , $day);
return $result;
}
}
?>
Lib_File1.php
复制代码 代码如下:
class Lib_File1
{
//文件目录
private $root = '/data/wwwroot/kkpromo/data/';
//文件后缀
private $suffix = '.log';
//文件句柄
private $hander=null;
//一次读取文件的最大记录数
private $limit=40000;
//每行读取的字节长度
private $length=1024;
//开始时间
private $startTime=0;
//内存使用基准点
private static $startMemory=0;
//
private $conn=null;
//
private static $init=null;
public static function instance()
{
self::$startMemory = memory_get_usage(true);
if(self::$init && is_object(self::$init))
{
return self::$init;
}
self::$init = new self();
return self::$init;
}
private function __construct(){}
public function setRoot($root)
{
if(!is_dir($root)) die($root.' ROOT DOES NOT EXIST');
$this->root = $root;
}
public function setSuffix($suffix)
{
$this->suffix = $suffix;
}
public function setLimit($limit)
{
if(!is_numeric($limit)) die($limit.' SHOULD BE NUMBERIC');
if(intval($limit) > 1000000) die($limit.' SHOULD BE LOWER THAN 1000000');
$this->limit = intval($limit);
}
private function _getFile($date , $appid , $op)
{
$filename = rtrim($this->root , '/').DIRECTORY_SEPARATOR.$date.DIRECTORY_SEPARATOR.$appid.'.'.$op.$this->suffix;
if(!file_exists($filename))
{
die($filename.' FILE DOES NOT EXISTS!');
}
if(!is_file($filename))
{
die($filename.' FILE DOES NOT EXIST!');
}
if(!is_readable($filename))
{
die($filename.' FILE ACCESS DENY!');
}
return $filename;
}
public function closeFile($date=null , $appid=null , $op=null)
{
if($op && $date && $appid)
{
if(is_object($this->hander[$date.'_'.$appid.'_'.$op]) || $this->conn[$date.'_'.$appid.'_'.$op])
{
fclose($this->hander[$date.'_'.$appid.'_'.$op]);
}
$this->conn[$date.'_'.$appid.'_'.$op]=null;
$this->hander[$date.'_'.$appid.'_'.$op]=null;
}
else {
if(is_array($this->hander) && $this->hander)
{
foreach ($this->hander as $key=>$val){
fclose($this->hander[$key]);
$this->conn[$key]=null;
$this->hander[$key]=null;
}
}
}
return true;
}
private function _openFile($date , $appid , $op)
{
$this->startTime = microtime(true);
if(isset($this->conn[$date.'_'.$appid.'_'.$op]) && $this->conn[$date.'_'.$appid.'_'.$op])
{
return $this->hander[$date.'_'.$appid.'_'.$op];
}
$filename = self::_getFile($date , $appid , $op);
if(($this->hander[$date.'_'.$appid.'_'.$op] = fopen($filename, 'r'))!=null)
{
$this->conn[$date.'_'.$appid.'_'.$op] = true;
return $this->hander[$date.'_'.$appid.'_'.$op];
}
else {
die('FILE OPEN FAILED!');
}
}
/**
* 功能:解析数据
* 格式: array('timestamp','mid','data');
* @param string $data
* @return boolean|array
*/
private function _parseData($data)
{
if(empty($data) || !is_string($data)) return false;
$result = array(
'timestamp'=>0,
'mid'=>0,
'data'=>array(),
);
$data = explode('|', $data);
if(count($data) $result['timestamp'] = $data[0];
$result['mid'] = $data[1];
$result['data'] = @json_decode($data[2] , true);
if(empty($result['timestamp']) || empty($result['mid'])) return false;
unset($data);
return $result;
}
/**
* TODO:读取单一文件
* @param string $date: 如(20140327)
* @param int $appid: 如(1000,9000)
* @param string $op:如(show,login , index)
* @param number $startNum 默认从第一行开始
* @param number $endNum 默认到$this->limit结束
* @param array $condition:array('mid'=>arrray() , 'ip'=>array() , ...) 过滤条件
* @param bool $jsonFlag:默认为true, 则保留jsondata字段;设为false,则去掉false字段
* @return array(count , diffTime , memory , data)
*/
public function readFile($date , $appid , $op ,$startNum=0 , $endNum=0 , $jsonFlag=false , $condition=array())
{
$data['data'] = "";
$data['count'] = 0;
$index = $startNum;
$startNum = empty($startNum) ? 0 : $startNum;
$endNum = empty($endNum) ? $this->limit : $endNum;
$hander = self::_openFile($date , $appid , $op );
$tmpindex=0;
if($hander)
{
//!feof($hander)
while ($tmpindex {
$tmp = fgets($hander , $this->length);
if(empty($tmp)) continue;
if($tmpindex =$startNum)
{
$tmp = self::_parseData($tmp);
if(empty($tmp)) continue;
//去掉jsondata
if(!$jsonFlag) { unset($tmp[2]); $condition= array(); }
//条件过滤
if($condition && is_array($condition) )
{
foreach ($condition as $key=>$val){
if(in_array($tmp['data'][$key], $condition[$key]))
unset($key , $val);
$data['count']++;
$data['data'][$index] = $tmp;
$index++;
}
}
else{
$data['data'][$index] = $tmp;
$index++;
$data['count']++;
}
}
if($tmpindex >= $endNum) break;
$tmpindex++;
unset($tmp);
}
fseek($hander , SEEK_END);
}
$data['diffTime'] = doubleval(microtime(true)) - doubleval($this->startTime);
$data['memory'] = doubleval((doubleval(memory_get_usage(true)) - doubleval(self::$startMemory))/1024/1024) . ' M';
return $data;
}
/**
* TODO:命令行下获取文件总记录数*
* @param string $date
* @param int $appid
* @param string $op
* @return array
*/
public function total_lineFile($date, $appid, $op)
{
$this->_openFile($date, $appid, $op);
$file = escapeshellarg($this->_getFile($date, $appid, $op)); // 对命令行参数进行安全转义
$line = `wc -l $file`;
if(preg_match("/(\d{1,})/", $line , $ret)){
$data['count']=$ret[1];
}else{
$data['count']=0;
}
$data['diffTime'] = doubleval(microtime(true)) - doubleval($this->startTime);
$data['memory'] = doubleval((doubleval(memory_get_usage(true)) - doubleval(self::$startMemory))/1024/1024) . ' M';
return $data;
}
/**
* TODO:统计{$data}.{$op}.log记录数
* @param string $date
* @param int $appid
* @param string $op
* @param array $condition
* @return array
*/
public function countFile($date , $appid , $op ,$condition=array())
{
$data['count'] = 0;
$hander = self::_openFile($date , $appid , $op );
if($hander)
{
while (!feof($hander))
{
$tmp = fgets($hander , $this->length);
$tmp = self::_parseData($tmp);
if(empty($tmp)) continue;
if($condition && is_array($condition) )
{
foreach ($condition as $key=>$val){
if(isset($tmp['data'][$key]) && $tmp['data'][$key] && in_array($tmp['data'][$key], $condition[$key])){
unset($key , $val);
$data['count']++;
}
}
}
else
$data['count']++;
unset($tmp);
}
fseek($hander , SEEK_END);
}
$data['diffTime'] = doubleval(microtime(true)) - doubleval($this->startTime);
$data['memory'] = doubleval((doubleval(memory_get_usage(true)) - doubleval(self::$startMemory))/1024/1024) . ' M';
return $data;
}
/**
* TODO:统计用户数
* @param string $date
* @param int $appid
* @param string $op
* @param bool $midflag :默认为false 则 mid返回空数组;如设为true,则mid数组不为空
* * @param bool $jsonFlag:默认为true, 则保留jsondata字段;设为false,则去掉jsondata字段
* @param array $condition
* @return : array:形如({"mid":[],"count":2181,"diffTime":0.0397667884827,"memory":"3.75 M"})
*/
public function countFileMID($date , $appid , $op , $midflag=false , $jsonFlag=false, $condition=array())
{
$count = self::total_lineFile($date , $appid , $op );
$index = ceil($count['count'] / $this->limit);
$result = array('mid'=>array() , 'count'=>0 , 'diffTime'=>0 , 'memory'=>0);
for ($i=0 ; $i {
$startNum = $this->limit*$i;
$endNum = $this->limit*($i+1);
$data = self::readFile($date , $appid , $op , $startNum , $endNum , $jsonFlag);
if($data['data'] && is_array($data['data']))
{
foreach ($data['data'] as $arr)
{
if($condition && is_array($condition)){
foreach ($condition as $key=>$val){
if(isset($arr['data'][$key]) && (in_array($arr['data'][$key] , $condition[$key]) || empty($condition[$key]))){
if(!isset($result['mid'][$arr['mid']])) { $result['mid'][$arr["mid"]] =1; $result['count']++; }
}
}
}
else {
if(!isset($result['mid'][$arr['mid']])) { $result['mid'][$arr["mid"]] =1; $result['count']++; }
}
}
}
unset($data['data'] , $data);
}
unset($index , $count , $condition , $data , $arr);
self::closeFile($date , $appid , $op);
$result['mid'] = array_keys($result['mid']);
//$result['count'] = count($result['mid']);
if(empty($midflag)) unset($result['mid']);
$result['diffTime'] = doubleval(microtime(true)) - doubleval($this->startTime);
$result['memory'] = (memory_get_usage(true) - self::$startMemory)/1024/1024 . ' M';
return $result;
}
/**
* TODO:跨时间段 统计参加$op用户数据
* @param string $date
* @param int $appid
* @param string $op
* @param number $day
* @param bool $midflag :默认为false 则 mid返回空数组;如设为true,则mid数组不为空
* @return array 形如("20140326":{"mid":[],"count":4571,"diffTime":0.0806441307068,"memory":"3.75 M"},
* "20140325":{"mid":[],"count":2181,"diffTime":0.0397667884827,"memory":"3.75 M"})
*/
public function getReturnUser($date , $appid , $op , $day=1 , $midflag=false)
{
$date_i=0;
for ($i =0; $i $date_i = date('Ymd' , strtotime($date)-$i*86400);
$result[$date_i] = self::countFileMID($date_i , $appid , $op , $midflag);
}
unset($date , $date_i , $appid , $op , $day);
return $result;
}
}
?>

핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

Video Face Swap
완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

인기 기사

뜨거운 도구

메모장++7.3.1
사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전
중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기
강력한 PHP 통합 개발 환경

드림위버 CS6
시각적 웹 개발 도구

SublimeText3 Mac 버전
신 수준의 코드 편집 소프트웨어(SublimeText3)

뜨거운 주제











Alipay PHP ...

기사는 PHP 5.3에 도입 된 PHP의 LSB (Late STATIC BING)에 대해 논의하여 정적 방법의 런타임 해상도가보다 유연한 상속을 요구할 수있게한다. LSB의 실제 응용 프로그램 및 잠재적 성능

JWT는 주로 신분증 인증 및 정보 교환을 위해 당사자간에 정보를 안전하게 전송하는 데 사용되는 JSON을 기반으로 한 개방형 표준입니다. 1. JWT는 헤더, 페이로드 및 서명의 세 부분으로 구성됩니다. 2. JWT의 작업 원칙에는 세 가지 단계가 포함됩니다. JWT 생성, JWT 확인 및 Parsing Payload. 3. PHP에서 인증에 JWT를 사용하면 JWT를 생성하고 확인할 수 있으며 사용자 역할 및 권한 정보가 고급 사용에 포함될 수 있습니다. 4. 일반적인 오류에는 서명 검증 실패, 토큰 만료 및 대형 페이로드가 포함됩니다. 디버깅 기술에는 디버깅 도구 및 로깅 사용이 포함됩니다. 5. 성능 최적화 및 모범 사례에는 적절한 시그니처 알고리즘 사용, 타당성 기간 설정 합리적,

세션 납치는 다음 단계를 통해 달성 할 수 있습니다. 1. 세션 ID를 얻으십시오. 2. 세션 ID 사용, 3. 세션을 활성 상태로 유지하십시오. PHP에서 세션 납치를 방지하는 방법에는 다음이 포함됩니다. 1. 세션 _regenerate_id () 함수를 사용하여 세션 ID를 재생산합니다. 2. 데이터베이스를 통해 세션 데이터를 저장하십시오.

PHP 개발에서 견고한 원칙의 적용에는 다음이 포함됩니다. 1. 단일 책임 원칙 (SRP) : 각 클래스는 하나의 기능 만 담당합니다. 2. Open and Close Principle (OCP) : 변경은 수정보다는 확장을 통해 달성됩니다. 3. Lisch의 대체 원칙 (LSP) : 서브 클래스는 프로그램 정확도에 영향을 미치지 않고 기본 클래스를 대체 할 수 있습니다. 4. 인터페이스 격리 원리 (ISP) : 의존성 및 사용되지 않은 방법을 피하기 위해 세밀한 인터페이스를 사용하십시오. 5. 의존성 반전 원리 (DIP) : 높고 낮은 수준의 모듈은 추상화에 의존하며 종속성 주입을 통해 구현됩니다.

시스템이 다시 시작된 후 UnixSocket의 권한을 자동으로 설정하는 방법. 시스템이 다시 시작될 때마다 UnixSocket의 권한을 수정하려면 다음 명령을 실행해야합니다.

phpstorm에서 CLI 모드를 디버그하는 방법은 무엇입니까? PHPStorm으로 개발할 때 때때로 CLI (Command Line Interface) 모드에서 PHP를 디버그해야합니다 ...

정적 바인딩 (정적 : :)는 PHP에서 늦은 정적 바인딩 (LSB)을 구현하여 클래스를 정의하는 대신 정적 컨텍스트에서 호출 클래스를 참조 할 수 있습니다. 1) 구문 분석 프로세스는 런타임에 수행됩니다. 2) 상속 관계에서 통화 클래스를 찾아보십시오. 3) 성능 오버 헤드를 가져올 수 있습니다.
