I have all my images saved in the root directory where the normal user can't access. I randomly generate all the filenames, so I don't want them to know the path or name of the file. Currently, I have the img
element as so:
<img src="get_image.php?id=1">
I have my get_image.php
page as so:
<?php
include_once 'includes/db_connect.php';
include_once 'includes/functions.php';
$uploaddir = '/root/......./uploads/'; //Direct path from root to folder holding files
$id = $_GET['id'];
if(!is_numeric($id)) {
die("File id must be numeric");
}
// A QUICK QUERY ON A FAKE USER TABLE
$stmt = $mysqli->prepare("SELECT `name`, `mime` FROM `uploads` WHERE `filmId`=?");
$stmt->bind_param("i", $id);
$stmt->execute();
$stmt->bind_result($name, $mime);
// GOING THROUGH THE DATA
while($stmt->fetch()) {
header("Content-Type: " . $mime);
readfile($uploaddir.$name);
}
?>
If there someway I can do this? I don't want to call the image file src directly like so:
<img src="../../../uploads/file.jpg"> <!-- I don't want to do this -->
Doing it that way will give the user (or attacker) a hint of where I keep my uploaded files. These images are user-uploaded, so if an attacker were to upload an image with malicious code (even though I have lots of code checking and validating the file), they wouldn't know where that file was saved.
Also, I'm new to web development and keeping it secure. If you have any hints or pointer to add onto what I have to make my webpage more secure, please feel free. Thanks!
I'm using this link to make this functionality secure.
SOLUTION:
Instead of:
header("Content-Type: " . $mime);
readfile($uploaddir.$name);
I put this:
header("Content-Type: " . $mime);
$contents = file_get_contents($uploaddir . $name);
echo $contents;
and it works.