Using a (relatively) simple method with session data (the user),
fopen() and
fpassthru(), you can create a script to restrict user access to images, e.g.
Code: Select all
<?php
// image.php
// start the session
session_start();
// image base path, out of web root entirely
define('IMG_BASE_PATH', '/path/to/images/');
// default $imagefile value
// if the image name was passed in the GET string, set; if not, set to NULL
// value will be tested later
if ( isset($_GET['img']) ) {
$imagefile= IMG_BASE_PATH. htmlspecialchars($_GET['img']);
}
else {
$imagefile= NULL;
}
// check the user login (very basic check)
if ( !isset($_SESSION['user']) ) {
// user not verified
// bogus image file for non-subscribers
$imagefile= IMG_BASE_PATH.'baduser.jpg';
}
elseif ( !isset($imagefile) || !is_file($imagefile) ) {
// user is verified, but image not specified or invalid
// show 'image not here' or whatever image you like
$imagefile= IMG_BASE_PATH.'not_here.jpg';
}
// whatever the outcome of the above, we output an image
// binary safe call to fopen
$fp= fopen($imagefile, 'rb');
// set content type to image type
header("Content-type:image/jpg");
header("Content-length:" .filesize($imagefile));
// fpassthru dumps the image contents
fpassthru($fp);
exit;
?>
and the calling page
Code: Select all
<html>
<body>
<img src="image.php?img=bluesky001.jpg" />
</body>
</html>
You can see that the script checks the GET string for the image file name, then checks the user validity. If the user wasn't logged in, send a 'baduser.jpg' image. If logged in, but with a bad image file, send something else. Otherwise, outputs the image requested. Can be easily modified to allow the calling script to check user login, etc. Probably a dozen ways to do this based around the same basic calls to fopen() and fpassthru(), but I like the idea of giving the user back 'some image' rather than a broken image, so you know the application works as intended.
You should have more checks in place than this, but it's a scratched together example.
All files are stored outside the web root and cannot be accessed by any user simply typing it into the URL. Note you could also have an array stored with valid image file names, and use
in_array() to check the validity of a correct file. You might also have the script check MIME type on the file requested and not hardwire a type (like image/jpg).