php - Get the current script file name

ID : 10202

viewed : 28

Tags : phpfilephp

Top 5 Answer for php - Get the current script file name

vote vote

93

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

81

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.

vote vote

72

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

pathinfo(__FILE__, PATHINFO_FILENAME); 
vote vote

68

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.

vote vote

60

This might help:

basename($_SERVER['PHP_SELF']) 

it will work even if you are using include.

Top 3 video Explaining php - Get the current script file name

Related QUESTION?