簡體   English   中英

php中如何將相對目錄中的圖像包含到根目錄中

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM