I am trying to teach myself some php & mysql.
I am very interested in learning how to make php applications secure from hackers.
I just wrote this to do a simple log of ip addresses to a text file:
Quote:
<?php
function writeip($arg) {
$ip = getenv("REMOTE_ADDR");
$log = "\n$ip";
$fa = fopen("/home/iplog/iplog", "a");
$login = "$log";
fwrite($fa, $login);
$date = date("M, j, Y");
$time = date("g:i a");
fwrite($fa, " $arg on $date at $time \r\n");
fclose($fa);
}
?>
Notice how I try to use a path which is ABOVE my www, since I am told that such a location is harder to access and hack.
Today, I wrote this code to log IP addresses to a mysql table, and record how many attempts they have made. My idea is to detect unusual activity, and ban that ip address.
Quote:
<?php
include("/home/datainc/data.php");
$conn = mysql_connect("$location","$username","$password");
if (!$conn) die ("Could not connect MySQL");
mysql_select_db($database,$conn) or die ("Could not open
database");
$ip = getenv("REMOTE_ADDR");
$sql = "select * from iplog where ipaddress =\"$ip\" ";
$rs = mysql_query($sql,$conn) or die ("could not select database");
$num = mysql_numrows($rs);
if ($num == 0) {
$insert = "INSERT INTO iplog (ipaddress, logon, attempts, logoff, banned, prior1, prior2, prior3, prior4, prior5)
VALUES (\"$ip\", NOW(), 1, NOW(), \"N\", NOW(), NOW(), NOW(), NOW(), NOW() )";
mysql_query($insert) or die ("Could not add data to the table");
}
if ($num != 0) {
$sql = "update iplog set attempts = 0 where ipaddress = \"$ip\" and logon < date_add(curdate(), interval -1 day)";
mysql_query($sql, $conn) or die ("could not update attempts");
$sql = "update iplog set logon = now() where ipaddress = \"$ip\"";
mysql_query($sql, $conn) or die ("could not update attempts");
$sql = "update iplog set attempts = attempts + 1 where ipaddress = \"$ip\"";
mysql_query($sql, $conn) or die ("could not update attempts");
}
?>
I am really a beginner in sql, so my sql is very simple-minded. In the sql above, I reset the number of attemps if the logon date is more than a day or so old. Eventually, I shall add code to shife the dates down, so there is a record of the last 6 dates. It seems to me that all sorts of things are possible if one impliments this sort of audit trail.
I would appreciate any tips, advice, criticism.
Notice how I use INCLUDE to pull in my password/connect info for mysql, and my include file is above the /www.
My other project was to experiment with the session id for cookieless sessions.
One book that is very helpful to me is PHP IN EASY STEPS by Mike McGrath by Barnes & Noble.
I have also been experimenting with password protection on folders.
It took me a while to figure out the paths to get the password file above the /www.
I would enjoy hearing from anyone who shares my interest in such recreational programming.