在PHP中,我想将消息保存到文本文件并使用php读取日志文件。
这是我到目前为止所做的:
function LogUserActivity($LogFile, $Activity){
$UserIp = $_SERVER['REMOTE_ADDR'];
$TimeRef = date('d-m-Y H:i T');
$Handle = fopen($LogFile, 'a');
$Data = $UserIp.'|'.$TimeRef.'|'.$Activity.'~';
fwrite($Handle, $Data);
fclose($Handle);
}
function ReadUserActivity($LogFile){
global $log;
$LogFile = file_get_contents($LogFile);
$ExplodedLogFile = explode("~", $LogFile);
$ArrayNum = count($ExplodedLogFile);
$i = 0;
while ( $i <= $ArrayNum ){
$log[$i] = explode("|", $ExplodedLogFile[$i]);
$i++;
}
}
答案 0 :(得分:2)
我建议使用mySQL数据库:
http://www.thesitewizard.com/faqs/what-is-mysql-database.shtml
但如果你坚持使用它,这里有一些评论可以帮助你理解..
<?php
//create file ($LogFile -> filename, $Activity -> type of activity)
function LogUserActivity($LogFile, $Activity){
//get user's ip
$UserIp = $_SERVER['REMOTE_ADDR'];
//get time
$TimeRef = date('d-m-Y H:i T');
//create file
$Handle = fopen($LogFile, 'a');
//file contents
$Data = $UserIp.'|'.$TimeRef.'|'.$Activity.'~';
//write data to file
fwrite($Handle, $Data);
//close file
fclose($Handle);
}
//read data from file ($LogFile -> filename)
function ReadUserActivity($LogFile){
//variable for storing data on file
global $log;
//function to get log file's data
$LogFile = file_get_contents($LogFile);
//separate each entry and put it in an array
$ExplodedLogFile = explode("~", $LogFile);
//determine number of logs
$ArrayNum = count($ExplodedLogFile);
//incrementable variable
$i = 0;
//loop to search through logs
while ( $i <= $ArrayNum ){
//separate each log into the three parts it has and put them in an array inside the main array
$log[$i] = explode("|", $ExplodedLogFile[$i]);
//incrememnt i
$i++;
}
}
?>
答案 1 :(得分:1)
在每个脚本的开头调用LogUserActivity
,将要写入的文件传递给自己,并向自己传递一些消息。 E.g:
<?php
include('the-file-where-you-put-these-functions.php');
LogUserActivity('/tmp/example.log', 'Porkchop sandwitches!');
// the rest of your script
?>
调用您将用于检查日志的脚本中的其他功能。它将设置$ log变量,然后您可以随意打印出来。
或者只使用这个单线:
<?php
file_put_contents("/tmp/stuff.txt", "penguins", FILE_APPEND);
?>