【发布时间】:2012-11-17 11:16:40
【问题描述】:
我想将访问者的 ips 记录在一个文件中。然后在第二次尝试访问后,我不希望那个人在 10 天内访问该网站。如果他再次访问,那么我希望生成被禁止的消息。我可以用 mysql 数据库做到这一点,但我想通过文件处理来做到这一点。很紧急
【问题讨论】:
标签: php file-handling
我想将访问者的 ips 记录在一个文件中。然后在第二次尝试访问后,我不希望那个人在 10 天内访问该网站。如果他再次访问,那么我希望生成被禁止的消息。我可以用 mysql 数据库做到这一点,但我想通过文件处理来做到这一点。很紧急
【问题讨论】:
标签: php file-handling
我认为下面的代码 sn-p 会对你有所帮助:
define('IP_FILE', 'ip.php');//where to save IP data
define('LIMIT_SECONDS', 10*24*3600); // 10 days
//loading IP data
function loadIPFile() {
if (file_exists(IP_FILE)) {
require_once IP_FILE;
if (isset($ipArray) and is_array($ipArray)) {
return $ipArray;
}
}
return array();
}
//saving IP data
function saveIPFile($ipArray) {
$fp = fopen(IP_FILE, 'wb');
fwrite($fp, '<?php'.PHP_EOL);
fwrite($fp, '$ipArray = '.var_export($ipArray, true).';'.PHP_EOL);
fwrite($fp, '?>');
fclose($fp);
}
$ipArray = loadIPFile();//load info into array
$ip = $_SERVER['REMOTE_ADDR'];//visitor ip
//if such ip already exists and 10 days are not behind us redirect visitor
if (isset($ipArray[$ip]) and time() - $ipArray[$ip] < LIMIT_SECONDS) {
header('Location: banned_page.php');
exit;
}
else {
//else record new ip or new time
$ipArray[$ip] = $time;
}
//save IP information
saveIPFile($ipArray);
【讨论】:
如果您知道如何对数据库执行此操作,为什么还要对文件执行此操作?数据库基本上是一个文件,其功能位于顶部以帮助您访问数据。通过使用文件直接存储此类数据,您必须重写 MySQL 开箱即用的最小访问功能。为什么要重新发明轮子?
如果由于某种原因您无法访问 MySQL,那么也许可以尝试 SQLite http://php.net/manual/en/book.sqlite.php,它为您提供了许多 sql 类型的功能,但基于本地目录中的文件而不是 sql server。
【讨论】: