Hope your day is well.
I am currently trying to serve images with PHP that is not in the document root. This needs to be account specific so only specific users can access their images.
I am looking into X-Sendfile, but don't know if there's a better way. And so far I haven't got X-Sendfile to work.
I essentially need to be able to load an image so it can be referenced by HTML,
<img src="image.png" alt="">
Like that. So basically loading a file as image.png and then referencing it in HTML. I don't know a better way to do this if there is one, and how to do it all. Please help me.
Have a good day.
Generally what you want to do is:
Determine in what sort of way you can uniquely identify an image - in a way that doesn't leak information. A primary key so to speak. If the metadata for your images happens to be stored in a database, then each image likely already has a unique key (the primary key in that table; perhaps an auto_incrementing integer). It could be a string as well (or a UUID); it just has to be something you'd have no problem with exposing to the world (eg: no proper filenames like
birthday.jpg, nouser_john.png; ideally random values, but sequential ones (like mysqlSERIALs) are probably tolerable enough.Create a new "empty" page or route, lets call it say
/image.phpNow, in your original page (not the new
/image.phpyet, but the one you already had), you'll query the database to determine which images you want to show, and you use the unique id for those images to output something likeThat
<img>tag will cause the user to automatically make an additional request to that new/image.phppage, in order to download the image.Inside
/image.php, you'll take the requested ID from$_GET['id']. then you'll query the database to see if that is an image this person should be able to access (and perhaps also determine what thefilenameis, on the server). lets say your queries determined that:Now you just make php send out some headers to identify the upcoming data as being an image, and then just pass the file through:
and that's all there's to it.
The files can be located anywhere; both inside or outside the webroot (makes no difference), but PHP does need to have (filesystem)permissions to read from those files of course.