-1

I am trying to figure out a way through php to:

1) Get the name of the current page through it's url http://website.com/videos/a-great-video

2) Add it as a class to the body

<body class="a-great-video"></body>

3) I'm trying to create a PHP variable for the current page name but not sure how to grab it with PHP. The class will be added through PHP or at least that's the goal. If you have another way of doing this, please feel free.

Setup Information:

The server runs Apache 2.0 and uses mod_rewrite.

Example URL: http://localhost:8888/romwod/members/signup

What I'm trying to get: "signup" or "members-signup"

FLUXXUATE
  • 43
  • 1
  • 7

2 Answers2

0

To get your current page name use:

basename(__FILE__);

To include it in your body as a class:

<body class="<?php basename(__FILE__);?>">
jtorrescr
  • 627
  • 4
  • 13
  • I've added this in but since my site works with included files, if I add that code to the header.php file in my site, it returns header.php and not the page name. My site uses mod_rewrite so I'm trying to get the url name of the last piece of url. Basically the terms after the last "/" in the url. – FLUXXUATE Jul 11 '14 at 17:12
-1

Try this one:

<?php
    $url = $_SERVER['REQUEST_URI'];
    preg_match('|.*/(.*)|', $url, $matches);
?>
<body class = "<?php echo $matches[1]; ?>">
Valery Statichny
  • 593
  • 7
  • 22
  • I was not the person whom gave you the down, but $_SERVER['PHP_SELF']) returns the full path, not just the fine name – jtorrescr Jul 11 '14 at 17:13
  • Here is what it returned: /site/members/index and here is the original url http://localhost:8888/site/members/signup Is there anyway to get the rewritten page url? It uses mod_rewrite. Also is there any way to remove the trailing folder structure and only get the word "signup" as the output or even "members/signup". I can then just do a preg_replace to switch the "/" with "-" for the class names. – FLUXXUATE Jul 11 '14 at 17:15
  • It worked! You just have $url wrapped in quotes so it's reading it as a string. As soon as I remove the quotes it works like magic. If you can edit I'll mark it as the correct answer – FLUXXUATE Jul 11 '14 at 17:28
  • @ValeryStatichny if the page name at one point is "/thanks?id=HWZNK-4eaef238eccb81d6" how can I cut out everything after the "?" including the "?" – FLUXXUATE Jul 11 '14 at 17:55
  • Solved. if anyone needs this, it replaces everything after the question mark: $pagename_clean = substr($matches[1], 0, strpos( $matches[1], '?')); – FLUXXUATE Jul 11 '14 at 18:56
  • @user3768940, the task was to work with pages after mod_rewrite module. – Valery Statichny Jul 11 '14 at 21:04
  • You can modernize your regexp to |.*/(.*)\?.*| in such case. – Valery Statichny Jul 11 '14 at 21:07