0

I have a website that allows users to download files securely from S3 using a pre signed URL, however I want to log who has downloaded the files and when.

I have tried doing it by redirecting them to a different page which would then download the file automatically using a piece of JavaScript and then insert a record into a database table, but as soon as the script runs it stops the rest of the page loading stopping it redirecting back.

The JavaScript I am using is below:

<script>window.location.href = “url”</script>

Is it possible to do?

Nick Fallows
  • 171
  • 10

1 Answers1

3

I would recommend you to log the download on the PHP layer before you return the file to the user. You can get the information that you need, for example IP address or user information from the session, store it in a database, and then send the appropriate headers back to the user and start the file download. You shouldn't need to redirect the user to a new page.

Edit:

For example on your downloads.php you could:

<?php

// 1) Get the information that you would like to log
$user_agent = $_SERVER['HTTP_USER_AGENT']; 
$ip = $_SERVER['REMOTE_ADDR'];
$username = $_SESSION['username'];
// ...
// 2) Store the information on your database
// For example, add a MySQL INSERT here
// ...
// 3) Return the appropriate file to the user
// Code extracted from https://stackoverflow.com/questions/6175533/
$attachment_location = $_SERVER["DOCUMENT_ROOT"] . "/file.zip";
if (file_exists($attachment_location)) {
  header($_SERVER["SERVER_PROTOCOL"] . " 200 OK");
  header("Cache-Control: public"); // needed for internet explorer
  header("Content-Type: application/zip");
  header("Content-Transfer-Encoding: Binary");
  header("Content-Length:".filesize($attachment_location));
  header("Content-Disposition: attachment; filename=file.zip");
  readfile($attachment_location);
  die();        
} else {
  die("Error: File not found.");
} 

More information about PHP $_SESSION and $_SERVER here:
PHP $_SESSION
PHP $_SERVER

Edit 2:

Another header combination that may be useful:

header("Content-Disposition: attachment; filename=" . urlencode($file));    
header("Content-Type: application/force-download");
header("Content-Type: application/octet-stream");
header("Content-Type: application/download");
header("Content-Description: File Transfer");             
header("Content-Length: " . filesize($file));

More information about PHP headers:
PHP Headers

Yoryo
  • 270
  • 1
  • 6
  • 16