PHP实现类似tail命令读取最后n行的方法
原文出自: http://www.hly1980.cn/archives/118.html
需要分析日志时tail命令可是常需要用到的,可惜php内并没有提供类似的方法,所以自己实现了一个。
调用方式为tail($filename, $rows),每次默认读取1024字节作为缓冲,返回字符串数组,文件尾的行靠前(这里的行为和tail有所区别,如果需要以原序返回的请自行调用array_reverse)。
代码如下:
/**
* 读取文件最后若干行的数据
*
* @param string $filename
* 文件名
* @param string $rows
* 行数
* @param string $size
* 内存缓冲区大小,默认为1024字节
* @param string $ending
* 行尾分隔符,默认为\n
* @return array
* 读取成功则返回字符串数组,文件尾的字符串靠前,读取失败则返回false
*/
function tail($filename, $rows, $size = 1024, $ending = "\n") {
$ret = false;
if ($rows > 0 && $fp = fopen($filename, 'rb')) {
$pos = filesize($filename);
$ret = array();
flock($fp, LOCK_SH);
$data = '';
$found = 0;
while ($found < $rows) {
$pos = $pos - $size;
if ($pos < 0) {
$size = 1024 + $pos;
$pos = 0;
}
fseek($fp, $pos, SEEK_SET);
$data = fread($fp, $size) . $data;
$tmp = explode($ending, $data);
$count = count($tmp);
for ($i = 1; $i < $count; $i++) {
$ret[] = $tmp[$count - $i];
$found++;
if ($found >= $rows) {
break;
}
}
$data = $tmp[0];
if ($pos <= 0) {
break;
}
}
flock($fp, LOCK_UN);
fclose($fp);
}
return $ret;
}
相关文档:
用php生成excel文件
<?
header("Content-type:application/vnd.ms-excel");
header("Content-Disposition:filename=test.xls");
echo "test1/t";
echo "test2/t/n";
echo "test1/t";
echo "test2/t/n";
echo "test1/t";
echo "test2/t/n";
echo "test1/t";
echo "test2/t/n";
echo "test1/t";
e ......
经过2个星期的艰苦奋斗,终于小有成就。详细的流程我之前也有说过。所以不再提出。直接上代码,希望对大家有所帮助。
1.LOGIN.php
<?php
include_once"conn2.php";
$uname=$_POST['uname'];//接收传过来的用户名
$upwd=$_POST['upwd'];//接收传过来的密码并md5()
$sql="SELECT * from pv_master WH ......
getenv() 取得系统的环境变量(预定义变量)
$spager=getenv('SERVER_NAME');
“PHP_SELF”
当前正在执行脚本的文件名,与 document root 相关。举例来说,在 URL 地址为 [url]http://example.com/test.php/foo.bar[/url] 的脚本中使用 $_SERVER['PHP_SELF'] 将会得到 /test.php/foo.bar 这个结 ......
岗位职责
1、协助系统架构设计师进行系统架构设计工作;
2、承担Web应用核心模块的设计/实现工作;
3、承担主要开发工作,对代码质量及进度负责;
4、进行关键技术验证以及技术选型工作;
5、和产品经理沟通并确定产品开发需求;
岗位要求
1、具有互联网领域相关项目开发工作经验,对互联网业务以及技术有相 ......
PHP中的MYSQL常用函数总结
1、mysql_connect()-建立数据库连接
格式:
resource mysql_connect([string hostname [:port] [:/path/to/socket] [, string username] [, string password]])
例:
$conn = @mysql_connect("localhost", "username", "password") or dir( ......