Last active
June 16, 2018 16:27
-
-
Save kozmonaut/6604903 to your computer and use it in GitHub Desktop.
Example of how to use mongoDB for storing apache access logs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// Initialize connection | |
try{ | |
$mongo = New Mongo(); | |
$db = $mongo->test; | |
$collection = $db->logs; | |
; | |
} catch (MongoConnectionException $check){ | |
die ('Error msg: '. $check->getMessage()); | |
} | |
// Create array for saving logs | |
$request = array( | |
'ip_address' => $_SERVER['REMOTE_ADDR'], | |
'viewed_at' => new MongoDate($_SERVER['REQUEST_TIME']), | |
'page' => $_SERVER['SCRIPT_NAME'], | |
'req_method' => $_SERVER['REQUEST_METHOD'], | |
'protocol' => $_SERVER['SERVER_PROTOCOL'] | |
); | |
//Insert array to collection | |
$collection->insert($request); | |
$cursor = $collection->find(array(),array('ip_address','viewed_at','page','req_method','protocol')); | |
$cursor->sort(array(-1)); | |
?> | |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> | |
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> | |
<head> | |
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> | |
</head> | |
<div class="contentblock"> | |
<h3>Log management</h3> | |
<table> | |
<thead> | |
<tr> | |
<th>IP address</th> | |
<th>Date/Time</th> | |
<th>URL</th> | |
<th>Method</th> | |
<th>Protocol</th> | |
</tr> | |
</thead> | |
<tbody> | |
<?php while ($cursor ->hasNext()): | |
$post = $cursor->getNext(); ?> | |
<tr> | |
<td><?php echo $request['ip_address'];?></td> | |
<td><?php echo date('F j Y, g:i a',$request['viewed_at']->sec);?></td> | |
<td><?php echo $request['page'];?></td> | |
<td><?php echo $request['req_method']; ?></td> | |
<td><?php echo $request['protocol']; ?></td> | |
</tr> | |
<?php endwhile; ?> | |
</tbody> | |
</table> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment