假设这是您的网络文件夹的外观
root
/includes
/relativeroot1
/relativeroot2
在上面的文件夹中创建一个名为path.php
的includes
文件并插入以下内容
<?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 */
?>
在上面的文件夹中创建一个.htaccess
文件root
并插入以下内容
<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" />