在链接开头加上“/”以到达根文件夹在 PHP include 中不起作用。
例如“/example/example.php”
解决方案是什么?
include('example/example.php')
进行包含。include($_SERVER['DOCUMENT_ROOT'].'/example/example.php')
进行包含。我也遇到了这个问题。Paul Dixon的回答是正确的,但也许这会帮助你理解为什么:
这里的问题在于PHP是一种服务器端语言。当纯HTML文档可以基于您在服务器上设置的根URL访问文件时(例如,要从任何子目录访问图像,您将使用/images/example.jpg
从顶级目录向下进行访问),PHP实际上在使用include (/images/example.jpg)
时访问服务器根。
您设置的网站结构实际上位于Apache服务器中的文件系统中。我的网站根目录看起来像这样,从服务器根目录开始向下:
/home2/siteuserftp/public_html/test/
"test"代表您的网站根目录。因此,回答您的问题,为什么您的PHP include没有得到您想要的结果(它正按照应该的方式工作),是因为您正在要求PHP代码尝试在服务器根目录中查找文件,而它实际上位于您的网站HTML根目录中,看起来像上面那样。您的文件将基于“test /”的站点根目录,并且会像这样:/home2/siteuserftp/public_html/test/about/index.php。Paul Dixon提供的答案:"。include($_SERVER['DOCUMENT_ROOT'].'/example/example.php')
这正是可以解决你的问题的内容(不必担心寻找文档根目录来替换'DOCUMENT_ROOT',PHP将为您完成。只需确保您确实使用了'DOCUMENT_ROOT'即可)。
编辑:
有关'DOCUMENT_ROOT'和其他PHP SERVER变量的更多信息可以在此处找到。
include()函数(以及其他许多类似require()、fopen()等的函数)都是基于本地文件系统而非Web根目录工作的。
因此,当您执行以下操作时:
include( "/example/example.php" );
您正在尝试从您的*nix机器的根目录中包含文件。
虽然有很多方法可以处理您正在进行的操作,但Paul Dixon的建议可能是最好的选择。
public_html
的文件夹,通常您会在其中存储文件等。使用/
时,您将无法进入public_html
,而是直接进入主(不可访问)根目录。因此,请改用$_SERVER['DOCUMENT_ROOT']."/your/locati.on"
。stylesheets
/script
/href
标签。 - MR_AMDEV<?php
$docroot = 'http://www.example.com/';
include ($docroot.'inc-header.php');
?>
如果你在本地开发机上,可以通过在C:\Windows\System32\drivers\etc\hosts文件中添加以下内容来将你的域名指向localhost
127.0.0.1 www.example.com
allow_url_include = On
REGEDIT4
[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\DOS Devices]
"W:"="\\??\\C:\\Inetpub\\wwwroot"
- Andrey Baluevsky一些版本的PHP可能在文档根目录末尾有分隔符,而其他版本则没有。实际上,您可能希望使用:
$r = trim(filter_input(INPUT_SERVER, 'DOCUMENT_ROOT', FILTER_SANITIZE_STRING));
if (substr($r, 0, 1) == '/')
{
define("PATCH_SEPARATOR", "/");
}
else
{
define("PATCH_SEPARATOR", "\\");
}
if (substr($r, -1) == PATCH_SEPARATOR)
{
include_once ($r . 'example/example.php');
}
else
{
include_once ($r . PATCH_SEPARATOR . 'example/example.php');
}
这个答案并不是针对根目录的,但一种解决方法是使用 ../
来跳转到父目录。
当然,这种方法需要你了解文件结构。
例如,你可以使用:
include('../parent.php');
include('../../grand_parent.php');
/var/www/namedir/ <= root
/var/www/namedir/example/example.php <= file to include
-- directory when i need the include --
/var/www/namedir/dir1/page.php
/var/www/namedir/dir1/dirA/page.php
/var/www/namedir/dir1/dirB/page.php
我使用的解决方案很简单。 在“Dir1”之前获取路径。
类似这样
include (substr(dirname(__FILE__),0,strpos(dirname(__FILE__), '/dir1'))."/example/example.php");
/var/www/namesite/internalDirA/dirToInclude/example.php
/var/www/namesite/internalDirA/dir1/dirA/example.php
/var/www/namesite/internalDirA/dir1/dirB/example.php
至
/var/www/namesite/dirReserved/dirToInclude/example.php
/var/www/namesite/dirReserved/dir1/dirA/example.php
/var/www/namesite/dirReserved/dir1/dirB/example.php