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?
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, '.'));
}
substr
and strrchr
to strip off the last .
and everything behind it?
Nov 19, 2010 at 1:41
__FILE__
gives you the .php
file that line is in, you actually want $_SERVER['SCRIPT_NAME']
for the currently running top-level script (that which was invoked by the web server or directly on the command line)
Apr 28, 2011 at 17:34
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.
pathinfo($_SERVER["SCRIPT_FILENAME"], PATHINFO_BASENAME);
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.
SCRIPT_FILENAME
or REQUEST_URI
? I know they both are server vars but isn't REQUEST_URI
a user tampered value? it enables a "URI injection" threat
basename($_SERVER["REQUEST_URI"], ".php");
will return the folder's name if the link is of the form http://example.com/somefolder
. While basename($_SERVER['PHP_SELF'], ".php");
will always return the script's name, in this case index
.
Nov 3, 2014 at 19:10
This might help:
basename($_SERVER['PHP_SELF'])
it will work even if you are using include.
.php
at the end that the OP was trying to get rid of
Feb 24, 2013 at 0:05
Here is a list what I've found recently searching an answer:
//self name with file extension
echo basename(__FILE__) . '<br>';
//self name without file extension
echo basename(__FILE__, '.php') . '<br>';
//self full url with file extension
echo __FILE__ . '<br>';
//parent file parent folder name
echo basename($_SERVER["REQUEST_URI"]) . '<br>';
//parent file parent folder name with //s
echo $_SERVER["REQUEST_URI"] . '<br>';
// parent file name without file extension
echo basename($_SERVER['PHP_SELF'], ".php") . '<br>';
// parent file name with file extension
echo basename($_SERVER['PHP_SELF']) . '<br>';
// parent file relative url with file etension
echo $_SERVER['PHP_SELF'] . '<br>';
// parent file name without file extension
echo basename($_SERVER["SCRIPT_FILENAME"], '.php') . '<br>';
// parent file name with file extension
echo basename($_SERVER["SCRIPT_FILENAME"]) . '<br>';
// parent file full url with file extension
echo $_SERVER["SCRIPT_FILENAME"] . '<br>';
//self name without file extension
echo pathinfo(__FILE__, PATHINFO_FILENAME) . '<br>';
//self file extension
echo pathinfo(__FILE__, PATHINFO_EXTENSION) . '<br>';
// parent file name with file extension
echo basename($_SERVER['SCRIPT_NAME']);
Don't forget to remove :)
<br>
index.php
includes header.php
which in turn includes functions.php
, where log_location()
resides. I call log_location()
in header.php
, and then I run index.php
. All of the above function print out either function or index or domain or some variation of these. I wan't to know which PHP script called the function. Is it even possible (in a one-liner)? @begoyan
alex's answer is correct but you could also do this without regular expressions like so:
str_replace(".php", "", basename($_SERVER["SCRIPT_NAME"]));
hey.php-i-am-a-weird-filename.php
.
A more general way would be using pathinfo(). Since Version 5.2 it supports PATHINFO_FILENAME
.
So
pathinfo(__FILE__,PATHINFO_FILENAME)
will also do what you need.
$argv[0]
I've found it much simpler to use $argv[0]
. The name of the executing script is always the first element in the $argv
array. Unlike all other methods suggested in other answers, this method does not require the use of basename()
to remove the directory tree. For example:
echo __FILE__;
returns something like /my/directory/path/my_script.php
echo $argv[0];
returns my_script.php
\
Update:
@Martin points out that the behavior of $argv[0]
changes when running CLI. The information page about $argv
on php.net states,
The first argument $argv[0] is always the name that was used to run the script.
However, a comment from (at the time of this edit) six years ago states,
Sometimes $argv can be null, such as when "register-argc-argv" is set to false. In some cases I've found the variable is populated correctly when running "php-cli" instead of just "php" from the command line (or cron).
Please note that based on the grammar of the text, I expect the comment author meant to say the variable is populated incorrectly when running "php-cli." I could be putting words in the commenter's mouth, but it seems funny to say that in some cases the function occasionally behaves correctly. 😁
This works for me, even when run inside an included PHP file, and you want the filename of the current php file running:
$currentPage= $_SERVER["SCRIPT_NAME"];
$currentPage = substr($currentPage, 1);
echo $currentPage;
Result:
index.php
Try this
$file = basename($_SERVER['PATH_INFO']);//Filename requested
$_SERVER['SCRIPT_NAME']
be a better idea in case the script is being run on a terminal as suggested by @drew-stephens in the comments above
May 26, 2021 at 18:44
$file = basename($_SERVER['SCRIPT_NAME']);
May 30, 2021 at 17:43
Although __FILE__
and $_SERVER
are the best approaches but this can be an alternative in some cases:
get_included_files();
It contains the file path where you are calling it from and all other includes.
[0]
; so if fileA.php
includes fileB.php
which itself calls class ClassA.php
which uses this function; then all of the files above will have get_included_files()[0] === 'fileA.php'
. This is a great little function for traversing includes.
Example:
included File: config.php
<?php
$file_name_one = basename($_SERVER['SCRIPT_FILENAME'], '.php');
$file_name_two = basename(__FILE__, '.php');
?>
executed File: index.php
<?php
require('config.php');
print $file_name_one."<br>\n"; // Result: index
print $file_name_two."<br>\n"; // Result: config
?>
$filename = "jquery.js.php";
$ext = pathinfo($filename, PATHINFO_EXTENSION);//will output: php
$file_basename = pathinfo($filename, PATHINFO_FILENAME);//will output: jquery.js
__FILE__
use examples based on localhost server results:
echo __FILE__;
// C:\LocalServer\www\templates\page.php
echo strrchr( __FILE__ , '\\' );
// \page.php
echo substr( strrchr( __FILE__ , '\\' ), 1);
// page.php
echo basename(__FILE__, '.php');
// page
As some said basename($_SERVER["SCRIPT_FILENAME"], '.php')
and basename( __FILE__, '.php')
are good ways to test this.
To me using the second was the solution for some validation instructions I was making
also
indicates you are asking an additional question. Sheesh. Some peeps kids.