【问题标题】:Record who has downloaded what file from S3 using my PHP website使用我的 PHP 网站记录谁从 S3 下载了什么文件
【发布时间】:2018-07-31 08:55:32
【问题描述】:

我有一个网站,允许用户使用预签名 URL 从 S3 安全地下载文件,但是我想记录谁下载了文件以及何时下载了这些文件。

我已经尝试通过将它们重定向到不同的页面来做到这一点,然后该页面将使用一段 JavaScript 自动下载文件,然后将记录插入数据库表中,但是一旦脚本运行它就会停止其​​余的页面加载停止它重定向回来。

我使用的 JavaScript 如下:

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

可以吗?

【问题讨论】:

  • 为什么不只启用 S3 访问日志并处理它们?
  • @MitchDempsey 日志无济于事,因为它们只会记录访问 s3 存储桶的帐户,而不是数据库中的用户帐户

标签: javascript php amazon-s3


【解决方案1】:

我建议您在将文件返回给用户之前在 PHP 层记录下载。您可以从会话中获取所需的信息,例如 IP 地址或用户信息,将其存储在数据库中,然后将适当的标头发送回用户并开始文件下载。您不需要将用户重定向到新页面。

编辑:

例如,在您的 downloads.php 上,您可以:

<?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.");
} 

在此处了解有关 PHP $_SESSION 和 $_SERVER 的更多信息:
PHP $_SESSION
PHP $_SERVER

编辑 2:

另一个可能有用的标题组合:

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));

有关 PHP 标头的更多信息:
PHP Headers

【讨论】:

  • 我对此还是很陌生,我不确定你的意思
  • @NickFallows 我添加了一个简单的示例,可以帮助您理解我的意思...
  • 我也尝试使用未签名的 url 下载它,但它返回损坏
  • @NickFallows 您可能没有为您的文件使用正确的标题组合。我建议您浏览此链接:php.net/manual/en/function.header.php
猜你喜欢
  • 1970-01-01
  • 2010-12-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-11-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多