Capture IP and URL of referrer This code is adapted from /core/modules/statistics/statistics.php. It uses a JavaScript file that sends an uncached POST request to the server (to ensure the code within gets run for every page request).

I want my code within to capture the IP and URL of the referrer. I've tried many things to grab this information and write it to the log, but no luck.

Whatever I do, I get a variation on Error: Call to a member function *something* on null in.... Like, I'm not getting anything. For example, the below throws: Error: Call to a member function getClientIp() on null in main() (line 26 of....

Any ideas?

&lt;?php

/**
 * @file
 * Store access data.
 */

use Drupal\Core\DrupalKernel;
use Symfony\Component\HttpFoundation\Request;
// use Symfony\Component\HttpFoundation\RequestStack;
// use Symfony\Component\HttpFoundation;

chdir('../..');

$autoloader = require_once 'autoload.php';

$kernel = DrupalKernel::createFromRequest(Request::createFromGlobals(), $autoloader, 'prod');
$kernel-&gt;boot();

// $container = $kernel-&gt;getContainer;

// $request = $kernel-&gt;getContainer()-&gt;get('request_stack')-&gt;getCurrentRequest();
// $request = $kernel-&gt;requestStack-&gt;getCurrentRequest();

// $url = \Drupal::request()-&gt;server-&gt;get('HTTP_REFERER');

// $hostname = $request-&gt;getClientIP();
// $hostname = \Drupal::request()-&gt;getClientIp();

\Drupal::logger('sitelog')-&gt;notice(REQUEST_TIME);




Working code:

&lt;?php

/**
 * @file
 * Store access data.
 */

use Drupal\Core\DrupalKernel;
use Symfony\Component\HttpFoundation\Request;

chdir('../..');

$autoloader = require_once 'autoload.php';

$request = Request::createFromGlobals();
$kernel = DrupalKernel::createFromRequest($request, $autoloader, 'prod');
$kernel-&gt;boot();

$hostname = $request-&gt;getClientIP();
$url = $request-&gt;server-&gt;get('HTTP_REFERER');

\Drupal::logger('sitelog')-&gt;notice($hostname . ' - ' . $url);
You are almost there, here is a rewritten version of your code that should work:

&lt;?php

/**
 * @file
 * Store access data.
 */

use Drupal\Core\DrupalKernel;
use Symfony\Component\HttpFoundation\Request;

$autoloader = require_once 'autoload.php';

$request = Request::createFromGlobals();
$kernel = DrupalKernel::createFromRequest($request, $autoloader, 'prod');
$kernel-&gt;boot();

$client_ip = $request-&gt;getClientIP();
$headers = $request-&gt;server-&gt;getHeaders();
$referer_url = isset($headers['HTTP_REFERER']) ? $headers['HTTP_REFERER'] : '';

\Drupal::logger('sitelog')-&gt;notice($referer_url . '::' . $client_ip);


The main idea of the rewrite is to keep a reference to the HttpFoundation\Request from the very beginning and use if to get access to the parameters you want.

P.S.: Loading Symfony's components as well as booting Drupal's kernel may be an overkill for getting the client's IP and referer url, a simple php script could do that for you and write logs in a file.