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

如何将相关目录中的图像包含到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条)

报告相同问题?

悬赏问题

  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号
  • ¥50 安装pyaudiokits失败
  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?
  • ¥15 让node服务器有自动加载文件的功能