Limit images from direct download URL

I asked this question a while ago and got an answer that I thought would work, but I still have a problem. Perhaps this is what I am doing wrong, but I still do not have that right.

I want to restrict access to the entire directory. This directory contains images and PDF files. I need to create a link to pdf documents and insert images into the anchor tag. I was told to use the header for this. Using the header immediately outputs content that is great for a PDF document, but I need to insert 3 images from the same directory, and this does not work, because the header displays the image before html and the correct behavior.

I need a way to assign an image to a variable so that I can insert it where I need it after the html output. Any ideas?

Here is a link to my last question. How to restrict viewing of files in a directory

+1
source share
1 answer

Moving images outside of a public document Your host root or restricting access to them using .htaccess, for example

<FilesMatch "\.(gif|png|jpe?g)$">
  Order Allow,Deny
  Deny from all
</FilesMatch>

And send the images using a PHP script that will check the user's session and send the image only if the user is logged in.

//... your session checking routine just like in other scripts
if (!$logged) {
    //show error
    exit();
}

//Simple extention-to-mimetype map:
$mimetypes = array(
    '.jpg' => 'image/jpeg'
    '.jpeg'=> 'image/jpeg'
    '.pdf' => 'application/pdf'
    //add other extensions if needed
);

$file = basename($_GET['file']);    //preventing tricks with ../../anypath/anyfile
$ext = substr($file, strrpos($file, '.'));
if (file_exists($images_dir . $file) && isset($mimetypes[$ext]) ) {
    header('Content-Type: ' . $mimetypes[$ext]);
    echo file_get_contents($images_dir . $file);
} else {
    //show error
}
0
source

All Articles