【问题标题】:PHP, Date() and fopenPHP、Date() 和 fopen
【发布时间】:2012-07-28 07:22:39
【问题描述】:

我有一个错误系统,它将 date() 和错误插入到文件中:

$fp = fopen('errorFile.txt', 'a');
$message = "At the time: " . date("Y,m,d\|H:i:s") . " the following error took place: " . $e->getMessage();
fwrite($fp, $message);
fclose($fp);

我的问题:要从第二个参数的 fopen 开始,我需要 指针在开始处 并且查看了手册,我需要参数是只写把指针放在开头,不把文件截为零长度,我唯一找到的就是参数'a' 'a' 一切都很好,除了 每次都在末尾的指针,所以如果有人知道我可以使用什么参数,那么开始时的指针 并且它是 只写 并且它不会将文件截断为零长度,我也在尝试插入日期和 示例:这里的时间是18:00 插入的时间是15:00

【问题讨论】:

  • 你想把文本的内容放在最上面吗?
  • stackoverflow.com/questions/1760525/… 的可能重复项,有两种解决方案应该适合您
  • 因为如果你愿意,没有直接的方法可以做到。如果这是一个错误日志,您应该将新内容附加到文件末尾。

标签: php date fopen


【解决方案1】:

你可以试试这个逻辑

$message = "At the time: " . date("Y,m,d\|H:i:s") . " the following error took place: " . $e->getMessage();

$file = '/path/to/file';

$fileContents = file_get_contents($file);

file_put_contents($file, $message . $fileContents);

【讨论】:

  • is 如果您真的想这样做,我会建议您使用 a+ 并将其放在文件末尾以避免每个文件的开销写入操作以首先读取文件(随着时间的推移可能会变大)。如果您希望它显示从最新到最旧的消息,请编写一个小的阅读脚本来重新排序消息(我认为阅读的频率会比写作少) - 或在控制台上使用 tail
  • @MiDo 你可能是对的。我没有考虑这个划痕的性能
【解决方案2】:

要在开始时获得指针,您需要使用 fseek 函数,例如:

fseek($fp, 0);//place pointer at beginning 

fseek 之后你可以使用 fwrite 写入文件

$fp = fopen('errorFile.txt', 'a');
$message = "At the time: " . date("Y,m,d\|H:i:s") . " the following error took place: " . $e->getMessage();
 fseek($fp, 0);
fwrite($fp, $message);
fclose($fp);

关于 fseek 的更多细节可以参考PHP documentation

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-28
    • 1970-01-01
    • 1970-01-01
    • 2012-09-07
    • 1970-01-01
    相关资源
    最近更新 更多