Mobile app version of vmapp.org
Login or Join
Harper822

: Why does .htaccess not prevent a php script from accessing a file I ran into the following issue: On a website I want to prevent "unauthorized" access to a set of .xml files - the user has

@Harper822

Posted in: #Htaccess #Php

I ran into the following issue:

On a website I want to prevent "unauthorized" access to a set of .xml files - the user has to authenticate first. Now it would be possible for an authenticated user to type the URL of the file I don't want them to see. To prevent this, I created a simple php script that checks user authentication, then serves up the XML (with appropriate Content-type header).

At the same time, I put the following in the .htaccess file in the directory with .xml (and other) files:

<Files ~ "(.xml)">
Order allow,deny
Deny from all
Allow from xx.yy.zz.tt (IP address of server)
</Files>


This did the trick - .xml files were not longer "directly accessible", even for an "authenticated" user. But here is the thing I don't understand:


If I leave out the 'Allow from' line, the php script still manages to access the .xml files. It seems that the .htaccess is completely ignored when it comes to php.


So my question is two fold:


Is this expected behavior?
If so, then what method would one use to prevent a php script from accessing a particular file (or group of files)?


There is clearly a fundamental issue around .htaccess that I completely failed to grasp. Thanks for your insights.

10.02% popularity Vote Up Vote Down


Login to follow query

More posts by @Harper822

2 Comments

Sorted by latest first Latest Oldest Best

 

@Hamaas447

The .htaccess file is meant to be used by the HTTP Server, not PHP. Yet, you can setup PHP to read and adhere to the rules of the .htaccess file, if you need to do as such.

10% popularity Vote Up Vote Down


 

@Ann8826881

PHP doesn't work with the file over HTTP but directly on the filesystem, unless you access the file over HTTP using cUrl or file_get_contents('http://.../file.xml').

If you want to prevent the files from being accessed without the user being authenticated first, place the files outside the public directory and serve them from there.

/files/
/public_html/index.php


Now, for the files...

if ($user->isAuthenticated()) {
// set proper file header
// print out the file content from /files/
}


Documentation might help you get a grasp on what I have in mind... cn2.php.net/manual/en/function.readfile.php#48683
This way you'll prevent anonymous users from accessing the files as those are not stored in a publicly accessible directory.

10% popularity Vote Up Vote Down


Back to top | Use Dark Theme