提问者:小点点

如何根据用户名/学号显示只能由特定用户下载的文件?


我还是个初学者,所以我希望你能理解。 我一直在努力为我们的学院创建一个简单的学生门户。

我将制作一个学生门户,以便特别毕业的学生可以看到他们自己管理上传的软拷贝文件,如良好的道德,成绩证明/卡,和其他证书,很快他们就可以看到他们的成绩。 我完成了前端,注册,登录和输出过程,但我有一个很难的时间编码上传的文件/文件在网站。

  1. 如何上载特定学号的文件?
  2. 我可以将学生的编号与要上传的文件名匹配吗? 例如。 学生号码=123456789; 文件名:123456789.pdf

更多示例(场景):

1234568789号学生想下载文件,先注册,再登录,直接在主页(我不会创建下载页面)显示专门为他/她准备的文件,可供下载。


共1个答案

匿名用户

如果您只是将文档上传到遵循某种结构的目录中,并将其作为静态文件服务,那么您的系统将容易被学生猜测其他学生的文件路径并下载它们。

我认为理想情况下,您应该创建一个与学生表相关联的数据库表(attachments或其他)来存储文档路径(该路径是不可静态访问的,如果要直接访问它,您的Web服务器将返回403authorize),然后使用PHP检索并提供文档(如果该文档与数据库上的学生记录相关联)。

类似于:

$currentStudentId = 10; // This would come from the login session
$documentId = 73; // This could come as a URL param

// Fetch the attachment associated to the student from the DB
$query = 'SELECT filepath FROM attachments WHERE student_id = ? AND id = ?';
$stmt = $conn->prepare($query);
$stmt->bind_param('ii', $currentStudentId, $documentId); // Be sure to read about prepared statements if you're using mysqli
$stmt->execute();
$result = $stmt->get_result();
$row = $result->fetch_row();
$attachment = $row[0];

if (!$attachment) {
  // Return a 404 if the attachment doesn't exists or it's not associated to this student
  http_response_code(404);
  die('Attachment not foud');
} else {
  // Read and serve the file
  header('Content-type: application/pdf');
  header('Content-Disposition: attachment; filename="file.pdf"');
  readfile("{$attachment['filepath']}.pdf");
}

当然,在上传文件时,您需要在DB中创建attachments记录,该记录与student_id正确关联,并具有正确的filepath。 实际的文件名可以是随机的,没关系,只要它不与其他文件冲突,它是不可静态访问的,并且它正确地保存在attachments表中。