如何在php中将图像从相对目录包含到根目录
在上面的myphp.php脚本中,我试图包含relativeroot2 dir.Iam中的(img1.jpg),但我无法做到这一点,我如何才能包含它。当我说如何在php中将图像从相对目录包含到根目录,php,Php,在上面的myphp.php脚本中,我试图包含relativeroot2 dir.Iam中的(img1.jpg),但我无法做到这一点,我如何才能包含它。当我说$\u SERVER['DOCUMENT\u ROOT']时,我返回了一个值作为“ROOT”,它是如何包含的 “/relativeroot2/img1.jpg”>如果您的图表显示relativeroot2在根目录之外,但在同一父目录中,您可以在指定它之前使用。/上一级。您的图像标签中还有一个游离的双引号 |root | subdir 1
$\u SERVER['DOCUMENT\u ROOT']
时,我返回了一个值作为“ROOT”,它是如何包含的
“/relativeroot2/img1.jpg”>
如果您的图表显示relativeroot2在根目录之外,但在同一父目录中,您可以在指定它之前使用。/
上一级。您的图像标签中还有一个游离的双引号
|root
| subdir 1
| subdir 2
| subdir 3
| subdir 4
| subdir 5
| myphp.php
|relativeroot2(images directory)
img1.jpg
/../relativeroot2/img1.jpg“>
假设这就是您的web文件夹的外观
<img src ="<?php echo $_SERVER['DOCUMENT_ROOT']?>/../relativeroot2/img1.jpg">
在上面的includes
文件夹中创建一个名为path.php
的文件,并插入以下内容
root
/includes
/relativeroot1
/relativeroot2
<?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 */
?>
<?php require 'path.php' ?>
现在打开需要相对路径的文件,例如myphp.php
脚本,并在顶部插入以下内容
<IfModule php5_module>
php_value include_path "includes/"
</IfModule>
因此,要从您的案例中的任何文件请求任何相对路径,只需执行以下操作
root
/includes
/relativeroot1
/relativeroot2
<?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 */
?>
<?php require 'path.php' ?>
“title=“我的图像”/>
此目录在web根目录之外吗?@mikevoermans:是的,它在WebRoot之外。如果它在web根目录之外,则无法提供服务。您必须获取文件的内容并使用适当的mime类型头打印它。我会在PHP5.2中使用dirname(\uuuuu file\uuuu)
,或者在PHP5.3中使用常量\uu DIR\uuuu
,它与$\u服务器['DOCUMENT\u ROOT']的作用相同,看起来像\uu DIR\uuu
和dirname(\uu file\uu)
两者都返回当前执行文件的父目录。是这样吗$_服务器['DOCUMENT_ROOT']始终为您提供web根目录。当我想指定一个与当前文件无关的路径时(例如,指定许多不同文档使用的包含文件的位置)。@octern:Iam仍然无法使用您提供的代码访问图像