简体   繁体   English

fileinput上传和预览,保护文件

[英]fileinput upload and preview, protect files

What I am trying to find out is how to protect those files from unrestricted access. 我试图找出的是如何保护这些文件不受限制的访问。 I can understand that if these files are not in the public folder then the JQuery plugin won't be able to load them, but then everyone could guess the link in the end, and for example user one could just type the link and download some other user's images, is there any way to protect it? 我可以理解,如果这些文件不在公共文件夹中,那么JQuery插件将无法加载它们,但是每个人都可以猜到最后的链接,例如,用户可以只键入链接并下载一些其他用户的图像,有什么方法可以保护它?

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: getFile.php PHP: getFile.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();
}

and upload.php I won't post the code, but it basically, creates a folder with the userid as name in the web root folder so /uploads/{userid} and stores the files with their original name + a random string in the end to avoid same name file conflicts, then writes the path to the database, as well as it's original filename and the user id it belongs to. 和upload.php,我不会发布代码,但基本上,它会在Web根文件夹中创建一个以userid作为名称的文件夹,因此/ uploads / {userid}并将文件的原始名称+随机字符串存储在避免同名文件冲突,然后将路径及其原始文件名和所属的用户ID写入数据库。

Store the uploaded files outside of the webroot and use PHP to return them after checking the user has access. 将上传的文件存储在webroot之外,并在检查用户具有访问权限后使用PHP返回它们。 For example: 例如:

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

Wherever you want to request the image from the client side call this script with the path as a parameter. 无论您想从客户端请求图像的任何地方,都以路径为参数调用此脚本。 If you'd like to display the images inline you'll need to determine the correct MIME type and set it in the Content-Type header. 如果要内嵌显示图像,则需要确定正确的MIME类型并将其设置在Content-Type标头中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM