Monitor ip bandwidth transfer via php - how to make code?

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
szalinski
Forum Newbie
Posts: 14
Joined: Sat Oct 20, 2007 12:58 pm

Monitor ip bandwidth transfer via php - how to make code?

Post by szalinski »

After a considerable amount of googling, I basically was left with these two scripts, with some (but not much) of an idea on how to integrate them.

The first one:
This one seems to do what I want, but I don't know how to add to it to store the bandwidth usage (based on ip).

Code: Select all

<?php
function CalcBandwidth($buffer)
{
$file_size = strlen($buffer);
//store the file size in DB or file
return ($buffer);
}
ob_start('CalcBandwidth');
?>
This one, however, has the potential to allow the first script above to be integrated with it; but it logs the number of times a given file is downloaded, not total bandwidth:

Code: Select all

<?php
// change this value below
$cs_conn = mysql_connect('localhost', 'db_user', 'password');
mysql_select_db('db_name', $cs_conn);

mysql_query("CREATE TABLE IF NOT EXISTS `bandwidth` (
  `filepath` varchar(255) NOT NULL,
  `ipadres` varchar(15) NOT NULL,
  `size` datetime NOT NULL,
  UNIQUE KEY `filepath` (`filepath`,`ipadres`),
  KEY `ipadres` (`ipadres`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;");

$path = addslashes($_SERVER['REQUEST_URI']);
$ip = addslashes($_SERVER['REMOTE_ADDR']);
$dl = false;

$sql = sprintf("SELECT UNIX_TIMESTAMP(last_access) last_time FROM downloaded WHERE filepath = '%s' AND ipadres = '%s' ORDER BY last_access DESC", $path, $ip);
$res = mysql_query($sql);
if (mysql_num_rows($res) > 0) {
	$last_xs = mysql_result($res, 0, 'last_time')+3600;
	if ($last_xs < time()) {
		mysql_query(sprintf("REPLACE downloaded SET filepath = '%s', ipadres = '%s', last_access = NOW()", $path, $ip));
		$dl = true;
	} 
} else {
	$sql = sprintf("REPLACE downloaded SET filepath = '%s', ipadres = '%s', last_access = NOW()", $path, $ip);
	mysql_query($sql);
	$dl = true;
}

if ($dl) {
	$fullPath = $_SERVER['DOCUMENT_ROOT'].$path;
	if ($fd = fopen ($fullPath, "r")) {
		$fname = basename($fullPath);
		header('Content-type: application/octet-stream');
		header('Content-Disposition: filename="'.$fname.'"');
		header('Content-length: '.filesize($fullPath));
		header('Cache-control: private'); 
		while(!feof($fd)) {
			$buffer = fread($fd, 2048);
			echo $buffer;
		}
		fclose ($fd);
		exit;
	}
} else {
	header('HTTP/1.0 503 Service Unavailable');
	die('Abort, you reached your download limit for this file.');
}
?>
It shouldn't matter how many times I download a single file or an assortment of files, the script should just log the ip of the user and the amount of bandwidth they have transferred (into a MySQL database). I should be able to configure (via a variable or whatever) how much data should be allowed transferred until the script blocks off the ip for a given number of time (again configurable by a variable, e.g. $time_until_reset=3600, etc.).

So I would like if somebody could change whatever is necessary to do the following: when a user reuests a file, their ip is logged and the total amount of data they download is logged. When they have reached a critical amount, their ip's further requests are blocked until a given time has elapsed.

Any comments would be useful, and please don't hesitate to ask me if anything is unclear.

:)
szalinski
Forum Newbie
Posts: 14
Joined: Sat Oct 20, 2007 12:58 pm

Post by szalinski »

Still waiting on a reply to this...has anyone got any ideas? :(
User avatar
superdezign
DevNet Master
Posts: 4135
Joined: Sat Jan 20, 2007 11:06 pm

Post by superdezign »

What about image files, CSS files, and JavaScript files?

I think you should look more into monitoring bandwidth via the server rather than PHP.
szalinski
Forum Newbie
Posts: 14
Joined: Sat Oct 20, 2007 12:58 pm

Post by szalinski »

superdezign wrote:What about image files, CSS files, and JavaScript files?

I think you should look more into monitoring bandwidth via the server rather than PHP.
Yes thanks, but I'm using shared hosting so this is the only way to do it (in PHP anyway); and it's purely the transfer of certain filetypes i'm concerned about, so how would I go about it - could you show me some code? :)
User avatar
superdezign
DevNet Master
Posts: 4135
Joined: Sat Jan 20, 2007 11:06 pm

Post by superdezign »

Wait wait.. You want to block users from using bandwidth after they've used a certain amount??
Why would you want to do that?

By the way, you can't reliably retrieve the user's IP address, and some users IP addresses change.
szalinski
Forum Newbie
Posts: 14
Joined: Sat Oct 20, 2007 12:58 pm

Post by szalinski »

superdezign wrote:Wait wait.. You want to block users from using bandwidth after they've used a certain amount??
Why would you want to do that?

By the way, you can't reliably retrieve the user's IP address, and some users IP addresses change.
I'm fully aware of the IP pitfalls! I simply want to know the code so I can continue from there.

I just want a simple script that limits a users daily download bandwidth, that's all. It's the only method I can use at the moment from a shared hosting perspective. Obviously if I had access to Apache, I wouldn't need to ask this, because I could control it for any IP from the http.conf file etc.

I've looked on the net and only found the two you see in my first post, basically neither of them does exactly what I want, but if they were 'combined' (obviously not the scripts as they stand now!), then it would be perfect.

I dunno, maybe you feel responsible for limiting users if you show me how to make this script? :lol:

All I want to know is how to do it this way!

Thanks. :roll:
User avatar
s.dot
Tranquility In Moderation
Posts: 5001
Joined: Sun Feb 06, 2005 7:18 pm
Location: Indiana

Post by s.dot »

Read all files you want to monitor through a PHP script.. ie, send the header()'s for that file, and readfile() or file_get_contents() for them to download (search this board for downloading files, if you need help with that).

However, before you read the file to them (for downloading), store the size of the file somewhere, using filesize().

e.g.

download.php?file=image1.jpg (makesure you read the comments)

Code: Select all

/**
 * Using $_GET['file'] is insecure.  This is for example purpose only!
 */

//send the correct header type, based on the type of file (you may have to determine this yourself)
header('Content-type: image/jpeg');

//get the file size information
$filesize = filesize($_GET['file']);

//store it somewhere
mysql_query("UPDATE `users` SET `bandwidth_used`=`bandwidth_used`+$filesize WHERE `username` = 'bob' LIMIT 1") or die(mysql_error()); //example only, yours will be different

//read the file to them
echo file_get_contents($_GET['file'];
Set Search Time - A google chrome extension. When you search only results from the past year (or set time period) are displayed. Helps tremendously when using new technologies to avoid outdated results.
Post Reply