作为我的第一个PHP项目之一,我正在创建一个记录用户IP地址的IP日志记录脚本。由于某种原因,我的fwrite()函数似乎没有写入我的日志文件。
有人能帮助我吗?
<?php
// IP Logger Script
// By Sam Lev
// sam@levnet.us
$iplogfile = 'iplog.txt';
$ipaddress = $_SERVER['REMOTE_ADDR'];
$webpage = $_SERVER['SCRIPT_NAME'];
$timestamp = date('m/d/Y h:i:s');
$browser = $_SERVER['HTTP_USER_AGENT'];
$fp = fopen($iplogfile, 'a+');
chmod($iplogfile, 0777);
fwrite($fp, '['.$timestamp.']: '.$ipaddress.' '.$webpage.' '.$browser. "\r\n");
fclose($fp);
echo "IP ADDRESS: $ipaddress <br />\n";
echo "TIMESTAMP: $timestamp <br />\n";
echo "BROWSER: $browser <br />\n";
echo "Information logged to server. <br />\n";
?>
运行脚本后,iplog.txt仍为空白。一切都很好。
由于
答案 0 :(得分:6)
应该不是
$fp = fopen($file, 'a');
是
$fp = fopen($iplogfile, 'a');
?因为我没有看到$file
的定义。
答案 1 :(得分:2)
您的代码已签出,这是权限问题。
手动将文件chmod到0777
或在chmod($iplogfile, 0777);
$fp = fopen($iplogfile, 'a');
chmod 是标准服务器命令,不是PHP独有的。
答案 2 :(得分:-1)
<!-- Below Code Logs ONLY User's IP Address & Time Stamp & Browser Info To http://www.example.com/logs/ip-address-mainsite.txt -->
<?php
$iplogfile = 'full path to your logs goes here eg http://www.example.com/logs/ip-address-mainsite.txt';
$ipaddress = $_SERVER['REMOTE_ADDR'];
//load the file
$file = file_get_contents($iplogfile);
//check to see if the ipaddress is already in the file
if ( ! preg_match("/$ipaddress/", $file )) {
//nope, log it!
$webpage = $_SERVER['SCRIPT_NAME'];
$timestamp = date('d/m/Y h:i:s');
$browser = $_SERVER['HTTP_USER_AGENT'];
$fp = fopen($iplogfile, 'a+');
fwrite($fp, '['.$timestamp.']: '.$ipaddress.' '.$browser. "\r\n");
fclose($fp);
}
?>