Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Log a clicked (external) link to webserver log or a file

I have a website written in php. I have a lots of external links like:

<a href="http://example.com" target="_blank">

What i want is that if the user clicks on these kind of links it should log this somewhere. Preferred is the apache log. If not possible then log in a file.

How can I do this with (probably with js)?

like image 419
Geveze Avatar asked Dec 12 '25 20:12

Geveze


1 Answers

A simple solution to get it in apache log is to replace external links with something like:

<a href="tracker.php?url=http://example.com" target="_blank>

where tracker.php is on your server and simply redirects to the external site:

header('Location: ' . $_GET['url']);

This could be done manually, or you could replace the links client side using jQuery like:

$("a[target='_blank']").each(function(e){
  var href = $(this).attr("href"); 
  $(this).attr("href", "tracker.php?url=" + encodeURIComponent(href)); 
});

Fiddle of the above


Alternatively you can capture the click event using jQuery and make a request to your tracker.php file with the target URL as a query param and then redirect:

<a href="http://example.com" target="_blank">test</a>

// Click event for a tags with target='_blank' attribute
$("a[target='_blank']").click(function(e){
  e.preventDefault(); // Prevent the default behaviour (the link opening)
  var href = $(this).attr("href"); // Get the href attribute of the clicked element

  // Make a get request to tracker.php passing the encoded href
  $.get("tracker.php?url=" + encodeURIComponent(href), function(data) {
    window.open(href); // Open the link in a new window once http request is complete
  });
});

The downsides to this method are:

  • Right click + open in new tab won't be captured (nor middle mouse button clicks)

  • There will be a slight delay for the user during the http request.

Keyboard controls (focus + return key) will be captured.

For either of these to work you will need to ensure apache is configured to log GET requests, which it most likely will be by default, something like:

0.0.0.0 - - [20/Feb/2020:13:15:48 +0100] "GET /tracker.php?url=http://example.com HTTP/1.1" 200

like image 160
Brett Gregson Avatar answered Dec 14 '25 08:12

Brett Gregson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!