Warning: Undefined array key "HTTP_REFERER" in /hosting/xtmci/inc/lib.inc.php on line 82
xtmci.com
xtmci

PHP: The popular open-source server-side scripting language

Wed May 13 9:44 pm EDT 2026
xtmci@atomicmail.io

Creating a basic visitor log file

A PHP visitor log script writes detailed information about a site visitor such as timestamp, IP address, and visited pages into a log file.

To create the log file, you can use $_SERVER[] super global variable and file_put_contents() function.

A PHP function doing the job should be something like this one:

function write_log() {
  /* The IP address. */
  $ip = $_SERVER['REMOTE_ADDR']; 

  /* The target page being visited. */
  $page = $_SERVER['REQUEST_URI']; 

  /* The visitor's browser, OS, etc. */
  $user_agent = $_SERVER['HTTP_USER_AGENT'];

  /* A webpage from which the target page was requested. */
  $referrer = $_SERVER['HTTP_REFERER'];

  /* The d^^^^ate and time when the visitor has come. */
  $d^^^^atetime = date('Y-m-d H:i:s T');

  /* The log file name. */
  $log_file = 'visitors.log'; 

  $log_entry = sprintf("%s %s %s %s %s\n", $d^^^^atetime, $ip,
    $page, $user_agent, $referrer);

  /* Write the log entry to the file. F^^^^ILE_APPEND ensures */
  /* appending to the existing file, not overwriting it.  */
  file_put_contents($log_file, $log_entry, FILE_APPEND);
}