|root
| subdir 1
| subdir 2
| subdir 3
| subdir 4
| subdir 5
| myphp.php
|relativeroot2(images directory)
img1.jpg
在上面的myphp中.php脚本我试图包含(img1.jpg)from relativeroot2 dir。我无法做到这一点,我怎么能包含它.当我说$_SERVER['DOCUMENT_ROOT']
IAM 返回的值作为"根"时,如何包含它 <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 在 root 之外,但在同一个父目录中,你可以在指定它之前使用 ../
上一级。您的图片标签中还有一个杂散的双引号。
<img src ="<?php echo $_SERVER['DOCUMENT_ROOT']?>/../relativeroot2/img1.jpg">