Page 1 of 1

Remove String from $_SERVER[SCRIPT_NAME}

Posted: Sat Aug 21, 2010 7:45 am
by somecallmejosh
Hello,

This is my first post to this forum, and my first foray into PHP SERVER variables. I'm trying to dynamically create a class (CSS) in my main navigation based on the SCRIPT_NAME variable. In order to do so, I'd like to strip the directory path preceding the file name and the ".php" that follows.

This:
../directory/index.php
Becomes:
index

Taking a step back...
I've been defining a $bodyID variable on each page and have been using that as a trigger. For instance:

Code: Select all

<?php $body="index";  ?>

<ul>
   <li><a href="index.php" <?php if($bodyID == "index") {print 'class="active"';} ?>>Home</a></li>
   ...
</ul>
I'm looking for a solution that allows me to ditch the $bodyID method I'm currently using so I can take advantage of the SCRIPT_NAME variable to do the same thing in a more efficient manner.

Code: Select all

<ul>
   <li><a href="index.php" <?php if($_SERVER[SCRIPT_NAME] == "index") {print 'class="active"';} ?>>Home</a></li>
   ...
</ul>
I have a separate include that I call into all pages, and I'm thinking this would be the place to define something like this...

Code: Select all

     <?php $bodyID = do something to $_SERVER[SCRIPT_NAME] to remove directory path and file extension ; ?>
And then my navigation would once again look like this (without having to define the $bodyID variable on EVERY page of the site):

Code: Select all

<ul>
   <li><a href="index.php" <?php if($bodyID == "index") {print 'class="active"';} ?>>Home</a></li>
   ...
</ul>
I'd truly appreciate any help with the "do something to $_SERVER[SCRIPT_NAME] to remove directory path and file extension ;" statement from above.

Re: Remove String from $_SERVER[SCRIPT_NAME}

Posted: Sat Aug 21, 2010 8:36 am
by somecallmejosh
I've found the basename() function, and may be one step closer to a solution...

Code: Select all

  <?php $bodyID = basename($_SERVER['SCRIPT_NAME']) ; ?>
Unfortunately, this still leaves me with index.php (assuming I'm on the index.php page).
If I could just remove the .php, I'd be golden. Any suggestions?

Re: Remove String from $_SERVER[SCRIPT_NAME}

Posted: Sat Aug 21, 2010 9:29 am
by requinix
somecallmejosh wrote:Any suggestions?
Look harder at the documentation for basename.

Re: Remove String from $_SERVER[SCRIPT_NAME}

Posted: Sun Aug 22, 2010 3:44 pm
by somecallmejosh
Ahhh...

Code: Select all

<?php
     $scriptName= $_SERVER["SCRIPT_NAME"] ;
     $bodyID = basename($scriptNAme, ".php");
?>
Thanks a bunch for pointing me in the right direction. Much appreciated.