Easiest way to fetch filename

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
abeall
Forum Commoner
Posts: 41
Joined: Sun Feb 04, 2007 11:53 pm

Easiest way to fetch filename

Post by abeall »

Strangely I can't seem to find an easy way to determine the filename of the currently running script. I don't want the pathname, just the filename itself. Example, for a file in http://www.foo.com/bar/blah.php, I would want blah.php.

Basically, I have a series of php files which draw together multiple other files, one of which(the main body text) will be according to the current script filename. Example:

/pages/mypage.php
/pages/mypage.html
/inc/layout.html

What I want to do is use mypage.php to grab layout.html, do a str_replace of a <content/> tag using the contents of mypage.html

Thanks.
abeall
Forum Commoner
Posts: 41
Joined: Sun Feb 04, 2007 11:53 pm

Post by abeall »

feyd | Please use

Code: Select all

,

Code: Select all

and [syntax="..."] tags where appropriate when posting code. Your post has been edited to reflect how we'd like it posted. Please read:  [url=http://forums.devnetwork.net/viewtopic.php?t=21171]Posting Code in the Forums[/url] to learn how to do it too.[/color]


Here's what I'm doing:

Code: Select all

echo substr(array_pop(explode('/',$_SERVER['PHP_SELF'])),'',-4);

// or, broken apart:

$pagepath = $_SERVER['PHP_SELF']);
$pagepath_arr = explode('/',$pagepath);
$pagename = array_pop($pagepath_arr);
$filename = substr($pagename,'',-4);
Seems to work.


feyd | Please use

Code: Select all

,

Code: Select all

and [syntax="..."] tags where appropriate when posting code. Your post has been edited to reflect how we'd like it posted. Please read:  [url=http://forums.devnetwork.net/viewtopic.php?t=21171]Posting Code in the Forums[/url] to learn how to do it too.[/color]
User avatar
hawleyjr
BeerMod
Posts: 2170
Joined: Tue Jan 13, 2004 4:58 pm
Location: Jax FL & Spokane WA USA

Post by hawleyjr »

Code: Select all

echo basename( __FILE__ );
abeall
Forum Commoner
Posts: 41
Joined: Sun Feb 04, 2007 11:53 pm

Post by abeall »

basename()

Perfect. Thanks.
User avatar
RobertGonzalez
Site Administrator
Posts: 14293
Joined: Tue Sep 09, 2003 6:04 pm
Location: Fremont, CA, USA

Post by RobertGonzalez »

When using the __FILE__ constant, make sure to call it from the file you are in otherwise you will get the name of the file that the __FILE__ constant is actually in (on some systems). Another alternative is to use basename($_SERVER['SCRIPT_FILENAME']) or basename($_SERVER['PHP_SELF']).
Post Reply