You'll want to do this: Basically redirect all requests to a php file which then does the access control.
.htaccess
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /CheckAuthorizedToFile.php?file=$1 [NC,L,QSA]
CheckAuthorizedToFile.php
<?php
$basepath = '/path/to/images/';
$realBase = realpath($basepath);
$userpath = $basepath . $_GET['file'];
$realUserPath = realpath($userpath);
if ($realUserPath === false || strpos($realUserPath, $realBase) !== 0) {
//prevent directory traversal by exiting execution
exit();
}
if($_SESSSION['IsAllowedToViewFiles']===true)
{
$file = $_GET['file'];
$type = 'image/jpeg';
header('Content-Type:'.$type);
header('Content-Length: ' . filesize($file));
readfile($file);
}
else
{
echo "Not Autorized please login.";
}