[英]How to include the image from the relative Directory to a root Directory in php
|root
| subdir 1
| subdir 2
| subdir 3
| subdir 4
| subdir 5
| myphp.php
|relativeroot2(images directory)
img1.jpg
在上面的 myphp.php 腳本中,我試圖從 relativeroot2 目錄中包含 (img1.jpg)。我無法做到這一點,我該如何包含它。 當我說$_SERVER['DOCUMENT_ROOT']
iam 從那里返回值為“root”時如何包含它<img src ="<?php echo $_SERVER['DOCUMENT_ROOT']?>"/relativeroot2/img1.jpg">
假設這是你的 web 文件夾的樣子
root
/includes
/relativeroot1
/relativeroot2
在上面的includes
文件夾中創建一個名為path.php
的文件並插入以下內容
<?php
if (session_id() == '') {
session_start(); /* if not already done */
}
/* replace value below with appropriate header to root distance of this include file */
$header_to_root_distance = 1;
$header_dir = dirname(__FILE__);
$root_distance = substr_count($header_dir, DIRECTORY_SEPARATOR) - $header_to_root_distance;
if($_SERVER['SERVER_ADDR']){
$include_distance = substr_count(dirname($_SERVER['SCRIPT_FILENAME']), "/");
}else{
$include_distance = substr_count(dirname($_SERVER['SCRIPT_FILENAME']), "\\");
}
$r_path = str_repeat('../', $include_distance - $root_distance);
$_SESSION['r_path'] = $r_path;
/* Note - $r_path holds your relative url starting from the root folder */
?>
在上面的root
文件夾中創建一個.htaccess
文件並插入以下內容
<IfModule php5_module>
php_value include_path "includes/"
</IfModule>
現在打開你想要相對路徑的文件,例如你的myphp.php
腳本並在頂部插入以下內容
<?php require 'path.php' ?>
因此,從您的案例中的任何文件請求任何相對路徑。 只需執行以下操作
<img src="<?php echo $r_path.'relativeroot2/img.jpg' ?>" title="My Image" />
如果您的圖表顯示 relativeroot2 在根之外,但在同一父目錄中,您可以在指定它之前使用../
到 go 上一級。 您的圖片標簽中也有一個雜散的雙引號。
<img src ="<?php echo $_SERVER['DOCUMENT_ROOT']?>/../relativeroot2/img1.jpg">
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.