ARTICLE AD BOX
I want to allow directory index (list directory in browser) but only for users logged in via php. Users not logged in should not have any access.
Is it possible to log in to apache (AuthType Basic, AuthName, etc.) via php or is there another way to allow logged in users to use directory index but ban it for others.
e.g. website.com/dir/subdir will show directory listing for logged in users, but Access denied for all others.
I did express myself NOTsufficiently clear:
case:
the user logs in via php. some pages refer to content in directories this directories should be accessible via browser (e.g. button "open in browser").So, the question is not "can you do it in php or is it better to do in php". The question is: can php tell apache that there is a logged in user that has to get permission for directory index meanwhile all others can't get a directory index.
The best ChatGPT came up with is an htaccess file with that checks if there is a php-created "user file".
htaccess:
# Allow access only if the .user_logged_in file exists RewriteEngine On RewriteCond %{DOCUMENT_ROOT}/path/to/protected_directory/.user_logged_in -f RewriteRule ^ - [L] # Deny access if the flag file does not exist RewriteRule ^ - [F]PHP:
file_put_contents('/path/to/protected_directory/.user_logged_in', '');The problem is that it is not specific for the connection, as soon someone logs in the directory becomes visible for everyone.
The resulting idea is to create an htaccess file with authentication, etc. but php should do somehow the login process, e.g. manipulate some files or whatever.
But AFAIK that is not possible.
PHP work around:
php can write the .htaccess files. In the code below the php site creates a .htaccess file on-the-fly with index permission. Then an exec command restores the original htaccess file to remove the index permission with a delay of 0.5 seconds. php immediately redirects to the directory for directory listing. This works for single directories (within the directory listing it is not possible to open a subdir) and safety is compromised for half a second.
file_put_contents( 'hip/.htaccess', 'IndexOptions +FancyIndexing'); exec (' ( sleep 0.5; cd hip ; cp htaccess .htaccess ) > /dev/null 2>&1 &') ; header('Location: http://note.local/hip ');(To improve this approach htaccess should redirect to php, so that a click on a directory in the dir listing will show the dir, i.e. htaccess directs to php, php checks the login, creates the temp htaccess file, and redirects to the new directory. The temp htaccess file allows for indexing and does not redirect to php, so the directory is listed.)
