我试图找出的是如何保护这些文件免受不受限制的访问。我可以理解,如果这些文件不在公共(public)文件夹中,那么 JQuery 插件将无法加载它们,但是每个人最终都可以猜到链接,例如用户一可以只需键入链接并下载一些其他用户的图片,有什么办法可以保护吗?
JQuery:
function files(sort) {
$.ajax({
url: 'ajaxScripts/getFile.php',
type: "POST",
dataType: 'json',
data: {sort: sort},
async: false,
success: function (data) {
var preview = [];
var test = [];
$.each(data, function (key, item) {
preview.push(item.RelativePath);
console.log(item);
test.push({type: item.Type, caption: item.Title + ' ' + item.ExamDate, key: item.UserExamsID, url: 'ajaxScripts/deleteFile.php', downloadUrl: item.RelativePath});
});
$("#file-input").fileinput({
theme: 'fa',
uploadUrl: 'ajaxScripts/upload.php',
maxFileSize: 10000,
overwriteInitial: false,
initialPreview: preview,
initialPreviewAsData: true,
initialPreviewConfig: test,
purifyHtml: true
});
}, error: function (XMLHttpRequest, textStatus, errorThrown) {
console.log("XMLHttpRequest=" + XMLHttpRequest + "; textStatus=" + textStatus + "; errorThrown=" + errorThrown);
}
});
}
PHP: 获取文件.php
require_once 'DBconfig.php';
header('Content-Type: application/json');
session_start();
if (!isset($_SESSION['user_session'])) {
header("Location: /index.html");
die();
}
$sort = $_POST['sort'];
$userID = $_SESSION['user_session'];
try {
$stmt = $db_con->prepare("SELECT `RelativePath`,`Title`,`ExamDate`, `UserExamsID`, `Type` FROM `userexams` WHERE `UserID`=:userid AND UserExamsID>21 ORDER BY `ExamDate` ASC");
$stmt->bindParam(':userid', $userID, PDO::PARAM_INT);
$stmt->execute();
$res = $stmt->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($res);
} catch (PDOException $e) {
echo $e->getMessage();
}
和 upload.php 我不会发布代码,但它基本上会在 Web 根文件夹/uploads/{userid} 中创建一个以 userid 作为名称的文件夹,并使用原始名称+最后的随机字符串存储文件以避免相同name 文件冲突,然后写入数据库的路径,以及它的原始文件名和它所属的用户 ID。
最佳答案
将上传的文件存储在 webroot 之外,并在检查用户是否具有访问权限后使用 PHP 返回它们。例如:
// Let the browser know to expect a binary file
header('Content-Type: application/octet-stream');
session_start();
if (!isset($_SESSION['user_session'])) {
// Block access for users not logged in
header("HTTP/1.0 403 Forbidden");
die();
}
$userID = $_SESSION['user_session'];
$path = $_GET['path'];
// Check the logged in user is requesting one of their own files
// (Probably want something more elaborate; this is just an example)
if (strpos($path, '/uploads/' . $userID . '/') === false) {
header("HTTP/1.0 403 Forbidden");
die();
}
// Security check the request is valid (again, just one example)
if (strpos($path, '..') !== false) {
header("HTTP/1.0 403 Forbidden");
die();
}
// Return the image
readfile('/path/to/uploads' . $path);
无论您想从客户端请求图像,都可以使用路径作为参数调用此脚本。如果您想内嵌显示图像,则需要确定正确的 MIME 类型并将其设置在 Content-Type header 中。
关于php - fileinput上传和预览,保护文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47755476/