TransWikia.com

PHP for directory as opposed to a file

Stack Overflow Asked by J-Lo on December 18, 2021

I am using PHP to bring in the navbar into my pages. The following code allows me to set the active page so that I can style the links.

<?php if ($_SERVER['SCRIPT_NAME'] == "/caseStudies.php") { ?>

I am struggling with how to make it work on a drop-down menu. I have put the 4 pages into a sub-directory and I want to be able to style the title of the dropdown section when any one of the 4 pages is active.

I have tried:

<?php if ($_SERVER['SCRIPT_NAME'] == "/services/") { ?>

Services being the name of the directory, but it doesn’t work.

Is there another command other than 'SCRIPT_NAME' that will look for the directory rather than the file?

One Answer

Its because your $_SERVER['SCRIPT_NAME'] will be something like this: /services/page1.php and it is of course different than /services/. What you want to do is to check if $_SERVER['SCRIPT_NAME'] starts with /services/ and you can do that with strpos https://www.php.net/manual/en/function.strpos.php.

var_dump($_SERVER['SCRIPT_NAME']); // string(15) "/services/a.php"
var_dump($_SERVER['SCRIPT_NAME'] == "/services/"); //  bool(false)
var_dump(strpos($_SERVER['SCRIPT_NAME'], "/services/") === 0); // bool(true)

If you want directory it is also possible with dirname https://www.php.net/manual/en/function.dirname.php. So wrap $_SERVER['SCRIPT_NAME'] with dirname and you will get the dirctory and can just compare with /services:

var_dump(dirname($_SERVER['SCRIPT_NAME'])); // string(9) "/services"
var_dump(dirname($_SERVER['SCRIPT_NAME']) === '/services'); // bool(true)

Answered by blahy on December 18, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP