Hello, I just want to have a log file with user IP and agents of who is visiting my homepage.
I managed to modify a PHP script that does it, but Grav does not allow direct PHP inside pages
Could anybody make this script into a plugin that would run on mainpage.html.twig and write the log?
@marymaruda, You could see my Log Errors Plugin (logs 404 erros to file) as an example, the logic will be very similar. Of course you will need the correct event. see events reference here.
<?php
namespace Grav\Plugin;
use Grav\Common\Plugin;
use RocketTheme\Toolbox\File\File;
use Symfony\Component\Yaml\Yaml;
class LogerrorsPlugin extends Plugin
{
/**
* @return array
*/
public static function getSubscribedEvents()
{
return [
'onPageInitialized' => ['onPageInitialized', 1],
];
}
/**
* if page not found found saves data
*
*/
public function onPageInitialized()
{
$this->uri = $this->grav['uri'];
$this->savelog($this->uri->url);
}
/**
* Saves data to the log file
* - creates or append not found errors url, time and HTTP_REFERER
* - creates a summary and save it to file
*/
protected function savelog($url)
{
$date = new DateTime();
$rdate = $date->format('Y-m-d H:i:s');
$ip = $SERVER['REMOTEADDR'];
$agent = $SERVER['HTTPUSER_AGENT'];
$hostname = gethostbyaddr($SERVER['REMOTEADDR']);
$file = “bla.txt”;
$fh = fopen($file, ‘a’);
fwrite($fh, ‘/—’.$rdate.“—
”);
fwrite($fh, ‘| ’.$ip.' ‘.$hostname.“
”);
fwrite($fh, ’| ‘.$agent.“
”);
fwrite($fh, ’\—'.“
”);
fclose($fh);
}
}
---
My suggestion is to always run a copy of the site in a local environment, using MAMP for example, or another solution to run the site on your computer without affecting the live site.
That’s highly unlikely. I’ve been doing web development for 20+ years, running multiple webservers on a variety of local development machines and have yet to have a hacker connect and delete my computer
If you run your webserver locally and access the internet behind a router, then your webserver ports are not even accessible to the outside world. So someone couldn’t even connect to your computer even if they wanted to.
Also, webservers install with sensible defaults that ensure they are not ‘wide-open’ . They run server-side scripts, than unless are blatantly malicious are again not really something you can use to gain access to a computer.