简体   繁体   English

设置基本路径后,使用 PHP 从根目录外部显示 HTML 中的图像

[英]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/.我在这里开发一个应用程序,我在 HTML header 文件中设置了基本路径,在我的例子中,它是 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.该图像是私有的,因此与 public_html(它只是 HTML on Ubuntu lampp)文件夹平行保存。 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.因为,当我给出图像源的相对路径时,它不能 go 一级到所需目录。

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\">";

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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