Current 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
User avatar
po
Forum Newbie
Posts: 4
Joined: Sun Oct 23, 2005 9:24 am
Location: Victoria, BC, Canada

Current Filename?

Post by po »

Hi, I'm wondering how I can get the filename (without the extension and URL) of the current PHP file?
For example, if myfile.php is loaded, I want to somehow get the filename myfile in that page. I've taken a look at the basename() function, but I couldn't really figure out how to use it to get the current file.

-Thanks
User avatar
Chris Corbyn
Breakbeat Nuttzer
Posts: 13098
Joined: Wed Mar 24, 2004 7:57 am
Location: Melbourne, Australia

Post by Chris Corbyn »

Code: Select all

<?php

$file = basename(__FILE__);
preg_match('/^(.*?)\.[^\.]*$/', $file, $matches);
echo $matches[1];

?>
User avatar
po
Forum Newbie
Posts: 4
Joined: Sun Oct 23, 2005 9:24 am
Location: Victoria, BC, Canada

Post by po »

Sweet, thanks.
User avatar
AKA Panama Jack
Forum Regular
Posts: 878
Joined: Mon Nov 14, 2005 4:21 pm

Post by AKA Panama Jack »

Actually you really should use this if you want to get the name of the php program currently being executed.

Code: Select all

$_SERVER['PHP_SELF']
lilleman
Forum Newbie
Posts: 7
Joined: Thu Nov 17, 2005 4:55 pm
Location: Örebro, Sweden

Post by lilleman »

In this situation, I'd prefer to use the string functions instead of a regular expression:

Code: Select all

$name = substr(basename($filename = __FILE__), 0, strrpos($filename, '.'));
User avatar
Jenk
DevNet Master
Posts: 3587
Joined: Mon Sep 19, 2005 6:24 am
Location: London

Post by Jenk »

$_SERVER['PHP_SELF'] is tainted, long discussion well worth reading here: viewtopic.php?t=39853

as d11wtq replied, or:

Code: Select all

<?php

$filename = substr(basename(__FILE__), 0, strrpos(basename(__FILE__), '.'));

?>
Last edited by Jenk on Sat Nov 19, 2005 6:09 pm, edited 1 time in total.
User avatar
Jenk
DevNet Master
Posts: 3587
Joined: Mon Sep 19, 2005 6:24 am
Location: London

Post by Jenk »

lilleman wrote:In this situation, I'd prefer to use the string functions instead of a regular expression:

Code: Select all

$name = substr(basename($filename = __FILE__), 0, strrpos($filename, '.'));
That doesn't remove the extension :)

This works:

Code: Select all

$name = substr($filename = basename(__FILE__), 0, strrpos($filename, '.'));
lilleman
Forum Newbie
Posts: 7
Joined: Thu Nov 17, 2005 4:55 pm
Location: Örebro, Sweden

Post by lilleman »

That's what happens when you're too lazy to test the code, because you're sure it'll work... Image
Post Reply