简体   繁体   中英

Displaying Image in HTML using PHP from outside the root directory when base path is set

Here I am developing an application where I have set the basepath in the HTML header file, in my case, it is localhost/project/. Therefore, all links will get the basepath.

The problem arising now is, I want to display the image on the webpage. The image is private and therefore kept in parallel to public_html (it's just HTML on Ubuntu lampp) folder. Hence, I can't use the basepath to access these images.

Now, how can I display the image on the webpage? Because, when I give the relative path to the image source, it can't go 1 level up to the desired directory.

Any solution for this?

If I remove the basepath, I need to update hundreds of links in my project.

I tried -

$location = dirname($_SERVER['DOCUMENT_ROOT']); //it will give me the www folder on ubuntu
$image    = $location . '/profilePics/' . $retailerDetail['profilePic']; 

If the basepath was not set, it might work. But now, is there any other option?

I assume the script knows the location of the image:-), else it will need to be derived.

If it is relative to the script where you are accessing the image, just use the relative path to that script.

Once you have the path to the script, just read the image into an encoded string.

In the example below, the image can be in a private directory. As long as the script can access the image, it will work:

$privatePath = __DIR__ . "/../../../../home/user"
$headerImage = base64_encode(file_get_contents($privatePath . "/imageFile.png"));

$imgTag = "<img src=\"data:image/jpeg;base64," . $headerImage . "\" alt=\"altText\" title=\"title\" align=\"left\">";

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