Location: PHPKode > projects > phpBandwidth > phpbandwidth/acounting.php
<?
include("db_config.php");
include("db_$db[type].php");
include("user_functions.php");
if ($REMOTE_ADDR !== NULL){
	echo "Security violation";
	exit;
}

$conn = db_connect();
if ($conn === FALSE)
{
	echo "Cant connect to the database, have you connfigured it at <a href=\"db_install.php\">db_install.php</a> ?";
	exit;
}

// Get an array of all user id's
$users = db_get_users($conn);

if (count($users) < 1)
	die("users < 1!!!");

// Every thing seems to be ready, so lets get and clear the iptables listing
exec( "sudo /sbin/iptables -v -Z -xL  " , $iptables );

// Now log each user's bandwidth, if there has been any
while (list ($uid, $name) = each ($users)){
	// First bandwidth comming in
	$unlogged_bw = get_unlogged_bw($conn, $uid, "in", $iptables);
	if ($unlogged_bw)
		db_log_bw($conn, $uid, $unlogged_bw, "in");
	
	// Then bandwidth going out
	$unlogged_bw = get_unlogged_bw($conn, $uid, "out", $iptables);
	if ($unlogged_bw)
		db_log_bw($conn, $uid, $unlogged_bw, "out");
}

function db_log_bw($conn, $uid, $bw, $dir){
	global $conn, $db, $phpbandwidth;

	if ($counter < 0) // don't commit negative usage
		return 0;
	if ($dir == "in")
		$dir = "'t'";
	if ($dir == "out")
		$dir = "'f'";
	
	$result = pg_query ($conn, "SELECT counter, date_of_record from $db[bw_data] where uid=$uid AND \"in\" = $dir order by date_of_record desc limit 1;");
	
	if (!$result)
		echo "Select failed\n";

	$stored = pg_fetch_result($result, 0,0);
	$date = pg_fetch_result($result, 0,1);
	
	if (($stored + $bw) < $phpbandwidth[logging_resolution]){
		$result = pg_query ($conn, "UPDATE $db[bw_data] SET counter=".($bw + $stored).", date_of_record=now() WHERE uid=$uid AND date_of_record='$date' AND \"in\"=$dir\n");
		if (!$result)
				echo "Update failed: UPDATE $db[bw_data] SET counter=".($bw + $stored).", date_of_record=now() WHERE uid=$uid AND date_of_record='$date' AND \"in\"=$dir\n";
	}
	else{
		$result = pg_query ($conn, "INSERT INTO \"$db[bw_data]\" (uid, counter, \"in\") VALUES ($uid, $bw, $dir);");
		if (!$result)
			echo "INSERT failed:\nINSERT INTO \"$db[bw_data]\" (uid, counter, \"in\") VALUES ($uid, $bw, $dir);\n";
	}
}

?>
Return current item: phpBandwidth