PHP包含另一个目录的内容

PHP包含另一个目录的内容,php,Php,比如说, 我的网站是mywebsite.com。Public_html是主目录,在Public_html中有一个文件夹sub_dir和一个文件index.phpsub_dir包含以下文件: index.php、profile.php、contact.php 现在我想让public\u html目录像sub\u dir目录一样工作。比如,如果我访问public\u html/index.php,它将显示public\u html/sub\u dir/index.php的内容,而不会重定向到那里。如

比如说,

我的网站是
mywebsite.com
。Public_html是主目录,在
Public_html
中有一个文件夹
sub_dir
和一个文件
index.php
sub_dir
包含以下文件:

index.php、profile.php、contact.php

现在我想让
public\u html
目录像
sub\u dir
目录一样工作。比如,如果我访问
public\u html/index.php
,它将显示
public\u html/sub\u dir/index.php的内容,而不会重定向到那里。如果我访问
public\u html/profile.php
,它将显示
public\u html/sub\u dir/profile.php
的内容

如何执行此操作?

编辑:

我刚刚看到了您关于仅通过PHP执行此操作的评论,因为您无法更改
文档根目录
,而我仍然认为使用
.htaccess
将是一个更好的解决方案,您当然可以仅使用PHP执行此操作,下面是一个快速模型:

// Grab the URL parts
$url = parse_url("http://stackoverflow.com/posts/20420420");

// Redirect the user to the same path in `sub_dir`
header('Location: '. $url['scheme'] .'://'. $url['host'] .'/'. 'sub_dir'. $url['path']);
这会将用户重定向到
http://stackoverflow.com/sub_dir/posts/20420420

其他人建议使用,您可以将其与我上面的示例结合起来,动态调用
include()
sub\u dir
加载文件


我看到了一些这样做的方法

您可以使用PHP的函数,但这并不理想

您还可以使用
.htaccess
,例如:

<IfModule mod_rewrite.c>
    RewriteEngine on
    RewriteCond %{REQUEST_URI} !^sub_dir
    RewriteRule ^(.*)$ sub_dir/$1 [L]
</IfModule>

重新启动发动机
重写cond%{REQUEST_URI}^副处长
重写规则^(.*)$sub_dir/$1[L]
如果您将其置于
public\u html
中,请求将被传递到
sub\u dir
。因此,如果您请求
example.com/test.php
,您实际上将加载
example.com/sub_dir/test.php


你的主机设置是什么样的?根据您的环境,您还可以更改Web服务器
文档根目录

有一些方法可以做到这一点

  • 使用
    include()
  • 在public_html/index.php文件中

    <?php include_once 'sub_dir/index.php';?>
    
    <?php echo file_get_content('sub_dir/index.php');// Show as text?>
    

    包括“sub_dir/index.php”;或者使用mod_rewrite/.htaccess在目录下创建转发规则,将apache根目录指向subdir?也许
    include('../sub_dir/index.php')
    ?(如果您是公共的_html/index.php)。。等待您从哪里获取内容?我假设您选择了public_html作为根目录。如果我使用PHP的include,sub_dir的profile.PHP会像public_html的profile.PHP那样工作吗?我需要只使用PHP实现这一点,不允许使用.htaccess。不允许更改根目录。我必须实现这一点只使用PHP编程!