Apache Style Log with PHP

Small, short code snippets that other people may find useful. Do you have a good regex that you would like to share? Share it! Even better, the code can be commented on, and improved.

Moderator: General Moderators

Post Reply
KalvinB
Forum Newbie
Posts: 4
Joined: Tue May 23, 2006 11:34 am

Apache Style Log with PHP

Post by KalvinB »

Code: Select all

<?
$filename = "logs/access." . date("Y.m",time()) . ".log";

$fp = fopen($filename,"a");

$str = gethostbyaddr ( $_SERVER['REMOTE_ADDR'] );
$str .= " - -";
$str .= " [" . date("d/M/Y:G:i:s",time()) . " -0700]";
$str .= " \"" . $_SERVER['REQUEST_METHOD'] . " " . $_SERVER['REQUEST_URI'] . " HTTP/1.1\"";
$str .= " 200 1000";
if(isset($_SERVER['HTTP_REFERER'])) 
	$str .= " \"" . $_SERVER['HTTP_REFERER'] . "\"";
else
	$str .= " \"none\"";
$str .= " \"" . $_SERVER['HTTP_USER_AGENT'] . "\"";
$str .= "\r\n";
fwrite($fp,$str);
fclose($fp);
?>
I use GoDaddy for one of my sites which has 50GB of storage and 500,000MB of transfer but doesn't give raw access to logs and their web-stats tool is far less than spectacular. I use this code in log.php and include it in every page on the site. The only things it can't log accurately are the amount of data transfer and the status code of the request. It just uses code 200 and 1000 bytes transfered. GoDaddy does well enough telling me how much transfer there was and I only care about successful requests.

It works best for sites which are entirely PHP driven.

The logs are automatically rotated every month and they are in the standard Apache format so you can then download them and parse them with any log analyzer program you want that supports Apache logs.
User avatar
Hades
Forum Commoner
Posts: 35
Joined: Mon May 08, 2006 4:49 pm

Post by Hades »

Have you tried the google analytics system?

I've been using it on my own server for some time now and am very impressed with the stats it offers.
User avatar
Chris Corbyn
Breakbeat Nuttzer
Posts: 13098
Joined: Wed Mar 24, 2004 7:57 am
Location: Melbourne, Australia

Post by Chris Corbyn »

Hades wrote:Have you tried the google analytics system?

I've been using it on my own server for some time now and am very impressed with the stats it offers.
The stats are impressive, in fact we use it here. The only issue really is that it relies upon the client to provide you with the statistic through javascript (and you can't just "get" an account).
gf05856
Forum Newbie
Posts: 16
Joined: Sat Sep 02, 2006 11:17 am
Location: Belgium

Post by gf05856 »

Google analytics is now open for the general public for free (before only few could get an account!)
Post Reply