首页 > 解决方案 > 返回相对于站点根目录的路径,而不是服务器根目录

问题描述

为什么?

我需要检测给定路径是否包含目录app,但仅在站点根目录之后(即忽略完整的服务器路径,仅搜索实际站点内的路径)。

考虑以下路径:

我尝试过的...

我已经使用以下代码解决了上述问题:

// 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 中的内置类/方法来实现这一点,那么也请随时提出这些建议。

标签: phplaravellumen

解决方案


你应该能够做这样的事情:

助手将返回(即您的应用程序代码)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

帮助文档:https ://laravel.com/docs/5.8/helpers#method-app-path


推荐阅读