Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the current script file name

Tags:

file

php

People also ask

How do I get the current script name?

You can use __file__ to get the name of the current file. When used in the main module, this is the name of the script that was originally invoked. If you want to omit the directory part (which might be present), you can use os. path.

Which is used for PHP script name?

The inbuilt PHP function basename() returns the base name of a file if the path of the file is provided as a parameter to the basename() function. basename(__FILE__) : Current file name with PHP file extension.

What is __ FILE __ in PHP?

__FILE__ is simply the name of the current file. realpath(dirname(__FILE__)) gets the name of the directory that the file is in -- in essence, the directory that the app is installed in.

Which variable contains the name of the script?

The underscore variable is set at shell startup and contains the absolute file name of the shell or script being executed as passed in the argument list.


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, '.'));
}

When you want your include to know what file it is in (ie. what script name was actually requested), use:

basename($_SERVER["SCRIPT_FILENAME"], '.php')

Because when you are writing to a file you usually know its name.

Edit: As noted by Alec Teal, if you use symlinks it will show the symlink name instead.


See http://php.net/manual/en/function.pathinfo.php

pathinfo(__FILE__, PATHINFO_FILENAME);

Here is the difference between basename(__FILE__, ".php") and basename($_SERVER['REQUEST_URI'], ".php").

basename(__FILE__, ".php") shows the name of the file where this code is included - It means that if you include this code in header.php and current page is index.php, it will return header not index.

basename($_SERVER["REQUEST_URI"], ".php") - If you use include this code in header.php and current page is index.php, it will return index not header.