php - 返回相对于站点根目录的路径,而不是服务器根目录
问题描述
为什么?
我需要检测给定路径是否包含目录app
,但仅在站点根目录之后(即忽略完整的服务器路径,仅搜索实际站点内的路径)。
考虑以下路径:
/root/var/www/app/app/Http
真的/root/var/www/app/public
错误的C:\Users\john\Sites\example_com\www\app\Http
真的
我尝试过的...
我已经使用以下代码解决了上述问题:
// Normalise the directory separators in the document
// root
$document_root = str_replace('/', DIRECTORY_SEPARATOR, $_SERVER['DOCUMENT_ROOT']);
// Remove the '/public' path from the end, this should
// give us the path to the site root...
$site_root = str_replace(DIRECTORY_SEPARATOR . 'public', '', $document_root);
// Normalise the directory separators in the supplied
// path
$normalised_path = str_replace('/', DIRECTORY_SEPARATOR, $path['path']);
// Remove the site root from the beginning of the path
$stripped_path = str_replace($site_root, '', $normalised_path);
// Now we can run our tests...
我的问题
只是我还是上面的代码对于这样一个简单的任务看起来很荒谬?任何人都可以提出更好或更清洁的方法来实现这一目标吗?本质上,我试图从给定路径中剥离服务器根目录,以便给我一个相对于站点根目录的路径......
如果有一种方法可以使用 Laravel/Lumen 中的内置类/方法来实现这一点,那么也请随时提出这些建议。
解决方案
你应该能够做这样的事情:
助手将返回(即您的应用程序代码)app_path
的路径app
Str::contains('/root/var/www/app/app/Http', app_path()); // true
Str::contains('/root/var/www/app/public', app_path()); // false
Str::contains('C:\Users\john\Sites\example_com\www\app\Http', app_path()); // true
推荐阅读
- sql-server - Visual Studio SQL Server 数据比较“当 IDENTITY_INSERT 设置为 OFF 时,无法在表 'MyTable' 中插入标识列的显式值”
- excel - 将工作簿中的所有 Excel 选项卡合并到另一个工作簿上的最小选项卡中
- visual-studio-code - 在 VSCode 中格式化注释块
- python - 文本分类 - 处理不属于任何类别的文本
- c++ - 来自 C++ QAbstractListModel 的 Qml ListView 与 QThread 处理
- android - 如何在 Activity 之外使用 Image Uri?
- javascript - svg 可以在直接添加到 dom 时显示,但不能在其 base64 转换字符串作为 img 源传递时显示
- sql - SQL 正则表达式替换多个条件
- airflow - Airflow 2.0 - 重复键值违反唯一约束“ab_view_menu_name_key”..键(名称)=(DAG:xxx)已经存在
- jquery - JQuery Toggle show hide