Restrict file access only to logged in users

Asked

Viewed 971 times

1

There are only logged in users to view certain types of files?

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

  • Consider using HTACCESS to bar access to these file types, and make them available using PHP.

  • could give a sample of how it would look in PHP to release the file?

  • Yes I will put in the answer from the lock to the release

1 answer

1


First redirect all url calls to a php file to analyze it, in case we redirect everything that contains . tpl.

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

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

Create the PHP file "checkpermission.php" that will analyze whether or not the file will 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>';

}

Put the files ". php" and ". htaccess" in the project’s root folder or in the same folder where the index of your site is.

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

Note: For mod_rewrite and . htaccess must be enabled on your webserver and the same must be Apache, in the case of iis you should do the same only with webconfig. If you use XAMPP / WAMPP they work based on apache then just look for how to enable mod_rewrite in them, this option comes by default enabled but if it doesn’t work consider doing this check.

  • I will do the tests now, I’ll come back with the feedback for now thanks @Hiago Souza

  • If it helps, consider marking the answer as correct. And register on the site to collaborate ;)

  • Definitely friend, an Obs. need to inform the path of the files .tpl in the .htaccess or there is no need?

  • Not htaccess regular expression ". tpl$ " will pick up anything that ends with . tpl

  • The only modifications that I think you should make are the return messages for example the message to authenticate, the file does not exist... and what I’m sure you should modify is the condition that checks if the user is logged in (first IF).

  • Tendi, @Hiagosouza came across a little problem, if I access the file ../arquivo.tpl?_=89898989 can’t find

Show 1 more comment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.