PHP:在目录树中搜索文件并返回文件路径


PHP: Search Directory Tree for File and Return File Path

考虑以下工作流程:

用户向website.com/lolmyblogpost发出请求

我的。htacces都像…

RewriteCond %{REQUEST_URI} !=/index.php
RewriteRule .* /index.php

在index.php中,我将在模板的文件树中搜索lolmyblogpost.html返回:

/path/to/lolmyblogpost.html

那么在主模板中我可以:

{include file="{$pathToTemplate}"}

如何在目录树中搜索文件并返回文件路径?

您真正需要的是带有默认类型的" back"支持。像这样设置Apache虚拟主机:

<VirtualHost *:80>
    ServerName  example.com:80
    ServerAlias www.example.com
    DocumentRoot    "/path/to/root/dir"
    AddDefaultCharset UTF-8
    ErrorDocument 403 "/403.php"
    ErrorDocument 404 "/404.php"
    <Directory /path/to/root/dir>
            Options Indexes FollowSymLinks
            DefaultType application/x-httpd-php
            AllowOverride All
            Order deny,allow
            Allow from all
            AddOutputFilterByType DEFLATE application/javascript text/css text/html text/plain text/xml
            RewriteEngine On
            RewriteBase /
            RewriteCond %{REQUEST_FILENAME} !.index.ph.*
            RewriteRule ^(.*)$  /index.php
    </Directory>
</VirtualHost>

重要的一行是DefaultType application/x-httpd-php,这意味着您现在可以摆脱.php文件扩展名。

你现在可以使用http://example.com/this_is_a_php_page,也可以使用http://example.com/this_is_a_php_page/with_a_path_info_var

因此,在this_is_a_php_page(这实际上是一个没有扩展名的.php文件)上,您可以使用$_SERVER['PATH_INFO']来检查在URI中传递的变量。

编辑:

添加RewriteEngine和规则,将所有内容推送到index.php。这意味着您现在在服务器上有一个名为index.php的(真正的)单一页面,它需要检查$_SERVER['REDIRECT_URL']变量,以了解真正请求的内容。

例如,对http://example.com/a_page的请求现在将加载index.php,而将a_page传递给$_SERVER['REDIRECT_URL']。注意:此解决方案将把所有内容都推送到index.php。您需要包含一个异常,如:

 RewriteCond %{REQUEST_FILENAME} !.not_me_plz.*

允许所有以not_me_plz文件开头的文件"as expected".