Restrict file access to logged-in users only

1

How can only logged-in users view certain types of files?

Example, if a user types www.link.com/arquivo.tpl if it is logged in the system view, otherwise it displays error.

    
asked by anonymous 29.07.2015 / 14:35

1 answer

0

First redirect all url calls to a php file to do the analysis of the same, in the case we will redirect everything that contains .tpl.

  

To do this create the ".htaccess" file with the following content:

RewriteEngine On
RewriteRule \.tpl$ checkpermission.php [L]
  

Create the PHP file "checkpermission.php" which will analyze whether the file will or will not be available:

<?php

//Recupero o caminho absoluto do arquivo
$arquivo = $_SERVER['DOCUMENT_ROOT'].$_SERVER['REQUEST_URI'];

//Sua logica para verificar se o usuario esta logado...
if(isset($_SESSION['logado'])) { // faça o uso da sua verificação!

    //Verifico se o arquivo existe no servidor
    if(file_exists($arquivo))
    {

        //Caso exista disponibiliza o arquivo
        echo file_get_contents($arquivo);

    } else {

        //Caso não exista informo o usuario

        echo '<h1> Erro, o arquivo solicitado não existe!</h1>';

    }

} else {

    //Informo que ele não tem permissão
    echo '<h1>Arquivo disponível apenas para usuários autenticados!</h1>';

}
  

Place the ".php" and ".htaccess" files in the project root folder or in the same folder as the index of your site.

After that, just create the .tpl file with a content and run the tests

Note: In order to work, mod_rewrite and .htaccess must be enabled in your webserver and the same must be Apache, in case iis should do the same only with webconfig. If you use XAMPP / WAMPP they work based on apache so just look at how to enable mod_rewrite on them, this option is enabled by default but if it does not work consider doing this check.

    
29.07.2015 / 15:20