How to check if page is under a directory

If you are looking for technical assistance, be sure and include the version of Concrete and PHP that you are using.

PHP - 7.4
Concrete 8.5.7

Hello Team,

I am looking to add a code to the pages under some specific directories using a header file.

So I want to see if we can add an if condition in the header to check if the page is under a particular directory.

For e.g. I want to add code in all the pages that are under abc.com/xyz
abc.com/xyz/1 - should have code
abc.com/xyz/2 - should have code

so can anyone please help me with this?

Thanks in advance! :slight_smile:

There are different ways of doing it but, personally I find that the easiest is to compare paths.
What I would do is:

use Concrete\Core\Page\Page;

$parentPath = 'xyz/';

// Get the current page object
$currentPage = Page::getCurrentPage();
if (is_object($currentPage) && !$currentPage->isError()) {
    // get the path which will be /xyz/1/ /xyz/2/ etc...
    // and trim the '/' so it's easier to compare
    $path = trim($currentPage->getCollectionPath(), '/');

    // if you're using a PHP version older than 8 use
    // if (strpos($path, $parentPath) === 0)
    // instead of str_starts_with
    if (str_starts_with($path, $parentPath)) {
         // it is a child page of xyz
    }
}
2 Likes