如何使用 Linux 或 PHP 将文件保持在 1000 行?
我有一个文件,用于记录客户端的 IP 地址。他们想要保留文件的最后 500 行。它位于带有 PHP4 的 Linux 系统上(哦不!)。
我打算一次向文件添加一行新的 IP 地址。我们无权访问 cron,所以我可能需要让这个函数也执行行限制清理。
我正在考虑使用 exec('tail [some params]')
或者使用 PHP 读取文件,将其在换行符上分解为数组,获取最后 1000 个元素,然后将其写回。不过似乎有点内存密集型。
有什么更好的方法来做到这一点?
更新:
根据@meagar下面的评论,如果我想使用zip功能,我将如何在我的PHP脚本中做到这一点? (无法访问 cron)
if(rand(0,10) == 10){ shell_exec("find . logfile.txt [where size > 1mb] -exec zip {} \;") }
如果存在现有文件,zip 会自动枚举文件还是我需要手动执行此操作?
I have a file that I'm using to log IP addresses for a client. They want to keep the last 500 lines of the file. It is on a Linux system with PHP4 (oh no!).
I was going to add to the file one line at a time with new IP addresses. We don't have access to cron so I would probably need to make this function do the line-limit cleanup as well.
I was thinking either using like exec('tail [some params]')
or maybe reading the file in with PHP, exploding it on newlines into an array, getting the last 1000 elements, and writing it back. Seems kind of memory intensive though.
What's a better way to do this?
Update:
Per @meagar's comment below, if I wanted to use the zip functionality, how would I do that within my PHP script? (no access to cron)
if(rand(0,10) == 10){ shell_exec("find . logfile.txt [where size > 1mb] -exec zip {} \;") }
Will zip enumerate the files automatically if there is an existing file or do I need to do that manually?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
正如您所建议的,最快的方法可能是使用 tail:
(passthru 与 exec 的作用相同,只是它将整个程序输出输出到 stdout。您可以使用输出缓冲区捕获输出)
[编辑]
我同意之前的评论日志轮换会无限好...但是您确实声明您无权访问 cron,所以我假设您也无法执行 logrotate。
The fastest way is probably, as you suggested, to use tail:
(passthru does the same as exec only it outputs the entire program output to stdout. You can capture the output using an output buffer)
[edit]
I agree with a previous comment that a log rotate would be infinitely better... but you did state that you don't have access to cron so I'm assuming you can't do logrotate either.
logrotate
这将是“正确的”答案,但它不是这也很难设置。
logrotate
This would be the "proper" answer, and it's not difficult to set this up either.
您可以使用 count(explode("\n", file_get_contents("log.txt"))) 获取行数,如果等于 1000,则获取从第一个 \n 到末尾的子字符串,添加新的 IP 地址并再次写入整个文件。
和以a+模式打开文件写入新IP几乎是一样的。
You may get the number of lines using count(explode("\n", file_get_contents("log.txt"))) and if it is equal to 1000, get the substring starting from the first \n to the end, add the new IP address and write the whole file again.
It's almost the same as writing the new IP by opening the file in a+ mode.