Get the current script file name

Alex picture Alex · Nov 19, 2010 · Viewed 401.9k times · Source

If I have PHP script, how can I get the filename from inside that script?

Also, given the name of a script of the form jquery.js.php, how can I extract just the "jquery.js" part?

Answer

alex picture alex · Nov 19, 2010

Just use the PHP magic constant __FILE__ to get the current filename.

But it seems you want the part without .php. So...

basename(__FILE__, '.php'); 

A more generic file extension remover would look like this...

function chopExtension($filename) {
    return pathinfo($filename, PATHINFO_FILENAME);
}

var_dump(chopExtension('bob.php')); // string(3) "bob"
var_dump(chopExtension('bob.i.have.dots.zip')); // string(15) "bob.i.have.dots"

Using standard string library functions is much quicker, as you'd expect.

function chopExtension($filename) {
    return substr($filename, 0, strrpos($filename, '.'));
}