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:

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

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.

问题评论:

原文地址:

https://stackoverflow.com/questions/47755476/fileinput-upload-and-preview-protect-files

添加评论

友情链接:蝴蝶教程