可以使用此方法下载PHP脚本。 预防?

I am writing my app with this method. I want a private directory where cant be accesible via URL. So i have a htaccess where successfully redirect when you visit the photos folder. I have my files with this structure.

myApp | []photos | .htaccess | loadthephoto.php | home.php

when you visit the home.php, at one line i serve the image through loadthephoto.php. The code inside there is

    $resultLoad = getUserDetails($db,"photo","user_details",$_SESSION['theUserskey']);

    $photosName = $resultLoad['photo'];
    $file = 'photos/'.$photosName;
    $temp = explode(".", $photosName);
    $type = 'image/'.end($temp);

    header('Content-Type:'.$type);
    header('Content-Length: ' . filesize($file));
    readfile($file);
    exit();

It works fine. The problem is that it produce a html like this <img src="loadthephoto.php"> , and if you visit the url/loadthephoto.php make this downloadable. I do not want this.

First, is this way correct for serving "private" images ? If it can be implemented with this way, how can i make the loadthephoto.php for not be downloadable ?

Another way is to make the photos folder be accesible from url and producing the images with the classic URLs way.

You should check the file mime type and/or extension before serving it. Checking an extension is not recommended as anyone could upload an image with a txt extension.

You're halfway there with your code but you're making a mime type from an extension which is also unwise as image/jpg isn't a proper mime type it should be image/jpeg.

$resultLoad = getUserDetails($db,"photo","user_details",$_SESSION['theUserskey']);

$photosName = $resultLoad['photo'];
$file = 'photos/' . $photosName;

// Check mime type
$mime = mime_content_type($file);

$validMimes = ['image/jpeg', 'image/gif', 'image/png', 'image/svg+xml'];

// Refuse to serve invalid files
if (!in_array($mime, $validMimes)) {
    die('Invalid file type');
}

header('Content-Type:' . $mime);
header('Content-Length: ' . filesize($file));
readfile($file);
exit();