I need to detect whether a given path contains the directory app
but only after the root of the site (i.e. ignore the full server path, only search the paths within the actual site).
Consider the following paths:
/root/var/www/app/app/Http
true/root/var/www/app/public
falseC:\Users\john\Sites\example_com\www\app\Http
trueI have solved the above using the following code:
// 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...
Is it just me or does the above code seem ridiculous for such a simple task? Can anyone suggest a better, or cleaner, way of achieving this? Essentially, I am trying to strip the server root from a given path in order to give me a path relative to the site root...
If there is a way to achieve this using built in classes/methods in Laravel/Lumen then please feel free to suggest these too.
You should just be able to do something like this:
The app_path
helper will return the path of the app
(ie, your application code)
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
Helper Docs: https://laravel.com/docs/5.8/helpers#method-app-path