current page name

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
amirbwb
Forum Commoner
Posts: 89
Joined: Sat Oct 30, 2010 6:10 pm

current page name

Post by amirbwb »

hello I created a function that display the current page name (example: test.php), i'll be using this function in many pages, but I want to know if it does work for all pages and it won't make me troubles in certain conditions

Code: Select all

function page_name(){
	  $all_url=$_SERVER['SCRIPT_FILENAME'];
	  $all_url=explode(".php",$all_url);
	  $count_all=0;
	  $nophp=explode("/",$all_url[$count_all]);
	  $count_nophp=count($nophp)-1;
	  echo $nophp[$count_nophp].'.php';
	  }
thank you, waiting your replies =)
oscardog
Forum Contributor
Posts: 245
Joined: Thu Oct 23, 2008 4:43 pm

Re: current page name

Post by oscardog »

Code: Select all

<?php
function page_name() { //Should be named pageName!
$uri = $_SERVER['REQUEST_URI']; //Get everything after the extension, ie. example.com/test.php will return /test.php
$uri = substr($uri, 1); //Cut off the first /

$firstSplit = explode('/', $uri); //Split directories up
$dirCount = count($firstSplit) - 1; //Get the final part, our file, and remove one as arrays start at 0.

$pageName = explode('.', $firstSplit[$dirCount]); //Remove our extension

return $pageName[0];
}
?>
If you had PHP 5.3, you could use strstr's new third param which may be quicker than exploding... but the above will do what you require.

If your pages don't have an extension, i.e. http://www.example.com/this-is-my-page/, then the above won't work. If so, let me know and I'll write a revised copy.
User avatar
amirbwb
Forum Commoner
Posts: 89
Joined: Sat Oct 30, 2010 6:10 pm

Re: current page name

Post by amirbwb »

mm but in this case if I want to use this function in a page inside a subfolder example

....com/test/test.php

using the function page_name() will give me /test/test.php
oscardog
Forum Contributor
Posts: 245
Joined: Thu Oct 23, 2008 4:43 pm

Re: current page name

Post by oscardog »

The code I gave above won't. It will return the last part of the directory structure, minus the extension. I tried that on a sub directory and it worked fine.
Post Reply