How to prohibit viewing common images on a server via a direct link?

All images are in the folder www/uploads/ . For each user, the image assigned to him is displayed. But if some user creates a direct link to this folder or the files that are stored there, then he will be able to access other images.

What are the options:

  1. Store images and all other downloadable files by the user in the database. (not a good option)

  2. Deny access to the folder in which images and other files are stored, via the configuration file of the web server. But in this case, how can users see it?

    2 answers 2

    In principle, the solution looks like this:

    1. In .htaccess you redirect all requests for images to the controller.

    2. Processing the request, determining the rights to access the file and output the image if such rights exist.

    Minimum set .htaccess:

     RewriteEngine on Rewritebase / RewriteRule www/uploads/.*.png index.php?route=get_access 

    index.php:

     // Проверка привелегий на доступ в файлу if (!empty($_GET['route']) && $_GET['route'] == 'img_access') { header('Content-type:image/png'); // В REQUEST_URI будет храниться реальный URI запроса, // к примеру /www/uploads/test.png include __DIR__ . $_SERVER['REQUEST_URI']; } 

    This is the most simplified version, given as a demonstration. Of course, you will have to integrate the verification script into your engine / project.

    In .htaccess, all requests from the folder with pictures are redirected to index.php? Route = get_access so that you can connect a specific controller.

    • This is already close to how to do it. Thank. В .htaccess все запросы из папки с картинками перенаправляются по index.php? - the folder with pictures is closed for access through .htaccess. - Yury Svetlov
    • And you can not be hacked through this line of code - include __DIR__ . $_SERVER['REQUEST_URI']; include __DIR__ . $_SERVER['REQUEST_URI']; ? - Yury Svetlov
    • The folder itself is not closed, just all requests are redirected to index.php - Victor
    • Yes, in terms of security, the code is weak. It needs to be improved. In htaccess, redirect requests for images only, and in index.php, check for the presence of the file, its location, type - Victor

    For .htaccess there is a way to direct links to images. You need to use the RewriteCond directive.

    At the same time, you can also prohibit such links for specific domains or even specify a stub for the image or return an error 403 (depending on what you like).

    More details can be read here .

    • one
      Could you give me an example, but it’s not clear how to prohibit viewing images via a direct link? The question here is how to deny access to the image via a direct link from the side of the user, not hosting. - Yury Svetlov