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?


function files(sort) {
            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) {
                    test.push({type: item.Type, caption: item.Title + ' ' + item.ExamDate, key: item.UserExamsID, url: 'ajaxScripts/deleteFile.php', downloadUrl: item.RelativePath});
                    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);


require_once 'DBconfig.php';
header('Content-Type: application/json');
if (!isset($_SESSION['user_session'])) {
    header("Location: /index.html");
$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);
    $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.