简体   繁体   中英

Deny access to files in root directory from invalid users with php

I have a php web site. To access some pages the user must log in. I included a script to redirect to login page if is not authenticated. The user must look for images made specifically for them, other users should not see these images. To show these images I use img tag and they need to be in root directory, as far as i know. Is there any way to protect these files from invalid users?

Rather than linking to the image like <img src='1.jpg'/> link to a php which checks the user is logged in and echos out the bytes of the image <img src='getimage.php?imageId=1'/> ...and then put them somewhere not directly servable apart from that php page.

//check if user is logged in
if(!loggedIn())
{
   echo 'not logged in';
   exit();
}
$id = $_GET['imageId'];
$file = ... //use that id to look in db for image path
$type = 'image/jpeg';
header('Content-Type:'.$type);
header('Content-Length: ' . filesize($file));
readfile($file);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM