dongxiaolin2801 2012-04-10 16:47
浏览 36
已采纳

如何将相关目录中的图像包含到php中的根目录中

|root 
| subdir 1 
|   subdir 2
|     subdir 3
|       subdir 4
|         subdir 5 
|              myphp.php 

|relativeroot2(images directory)
   img1.jpg

In the above myphp.php script Iam trying to include the (img1.jpg)from relativeroot2 dir.Iam not able to do that how can i include it . when i say $_SERVER['DOCUMENT_ROOT'] iam returned with value as "root" from ther how can include it <img src ="<?php echo $_SERVER['DOCUMENT_ROOT']?>"/relativeroot2/img1.jpg">

  • 写回答

2条回答 默认 最新

  • dqwcdqs358367 2012-04-10 17:25
    关注

    Assuming this is how your web folder looks

     root
      /includes
      /relativeroot1
      /relativeroot2
    

    Create a file named path.php in the includes folder above and insert the following

    <?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 */
    
    ?>
    

    Create a .htaccess file in the root folder above and insert the following

    <IfModule php5_module>
        php_value include_path "includes/"
    </IfModule>
    

    Now open the file you want a relative path e.g your myphp.php script and insert the following at the top

    <?php require 'path.php' ?>
    

    So to request for any relative path from any file in your case. Just do the following

      <img src="<?php echo $r_path.'relativeroot2/img.jpg' ?>" title="My Image" />
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 springboot 3.0 实现Security 6.x版本集成
  • ¥15 PHP-8.1 镜像无法用dockerfile里的CMD命令启动 只能进入容器启动,如何解决?(操作系统-ubuntu)
  • ¥15 请帮我解决一下下面六个代码
  • ¥15 关于资源监视工具的e-care有知道的嘛
  • ¥35 MIMO天线稀疏阵列排布问题
  • ¥60 用visual studio编写程序,利用间接平差求解水准网
  • ¥15 Llama如何调用shell或者Python
  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?
  • ¥15 win10权限管理,限制普通用户使用删除功能
  • ¥15 minnio内存占用过大,内存没被回收(Windows环境)