Skip to content

Instantly share code, notes, and snippets.

@stalmok
Created December 5, 2012 15:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stalmok/4216203 to your computer and use it in GitHub Desktop.
Save stalmok/4216203 to your computer and use it in GitHub Desktop.
Restrict user access to content in folders using PHP and Apache
/**
* Original post: http://www.thebigblob.com/how-to-restrict-user-access-to-content-in-folders-using-php-and-apache-htaccess-files/
*/
# The .htaccess file
RewriteEngine on
RewriteBase /
RewriteCond %{REQUEST_URI} ^\/(path\/to\/some\/folder|dummy)\/.*$
RewriteRule !^((.*.php)|(.*\/))$ authorize.php
# The PHP file (authorize.php)
<?php
// Perform authentication and authorization here
if($hasAccessToFolder)
{
// Get the file
if(file_exists($_SERVER['DOCUMENT_ROOT'].$_SERVER['REQUEST_URI']))
{
// Open the file for reading
$fp = fopen($_SERVER['DOCUMENT_ROOT'].$_SERVER['REQUEST_URI'], 'r');
// Set mime type to header
header('Content-type: '.mime_content_type($_SERVER['DOCUMENT_ROOT'].$_SERVER['REQUEST_URI']));
// Send the contents of the file the browser
fpassthru($fp);
fclose($fp);
}
else
{
// File not found
die('File not found');
}
}
else
{
die('Access denined');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment