Page 1 of 1

current page name

Posted: Sat Aug 13, 2011 4:51 am
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 =)

Re: current page name

Posted: Sat Aug 13, 2011 6:33 am
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.

Re: current page name

Posted: Sat Aug 13, 2011 7:05 am
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

Re: current page name

Posted: Sun Aug 14, 2011 12:25 pm
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.