Return 相对于站点根目录的路径,而不是服务器根目录

Return a path relative to the site root, not server root

为什么?

我需要检测给定路径是否包含目录 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 中的内置 classes/methods 实现此目的,那么也请随时提出建议。

你应该可以做这样的事情:

app_path 助手将 return 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