basic recording of visitor / user ip address and browser

1:52 PM 10/10/2019

This tiny project is about recording / logging user (visitor) ip address and browser type into a log file on server.

log.js

<script>
	'use strict';
	var xhr = new XMLHttpRequest();
	xhr.open('POST', 'log.php');
	xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
	xhr.send('ua=' + encodeURIComponent(navigator.userAgent));
</script>
			

log.php

<?php
	if($_SERVER['REQUEST_METHOD'] == 'POST'){
		$date = new DateTime("now", new DateTimeZone('Asia/Jakarta'));
		$line = 'date: ' . $date->format("Y-m-d H:i:s T");
		$line .= ', ip: ' . $_SERVER['REMOTE_ADDR'];
		$line .= ', ua: ' . $_POST['ua'] . PHP_EOL;
		file_put_contents('visitor.log', $line, FILE_APPEND | LOCK_EX);
	}
?>
			

For parameter to be passed to DateTimeZone(), see following page at https://www.php.net/manual/en/timezones.php

visitor.log (auto created)

The resulting log file, which may look like below (page browsed with Firefox 70 browser).

date: 2019-10-27 06:38:42 WIB, ip: 111.222.333.444, ua: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:70.0) Gecko/20100101 Firefox/70.0
			

Comments