321

If I have PHP script, how can I get the filename of the currently executed file without its extension?

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

Flimm
  • 136,138
  • 45
  • 251
  • 267
Alex
  • 66,732
  • 177
  • 439
  • 641

18 Answers18

482

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, '.'));
}
alex
  • 479,566
  • 201
  • 878
  • 984
  • 1
    Why not simply use `substr` and `strrchr` to strip off the last `.` and everything behind it? – ThiefMaster Nov 19 '10 at 01:41
  • 11
    @ThiefMaster Because there is something built into PHP to handle file extensions. The wheel exists, and rolls well. – alex Nov 19 '10 at 02:08
  • 3
    But a regex might be more expensive! – ThiefMaster Nov 19 '10 at 11:42
  • @ThieMaster Show me some code for a website where this function is the bottleneck and I'll reconsider. – alex Nov 19 '10 at 12:08
  • @ThieMaster According to [my benchmark](http://codepad.org/eywKhKyY), the `strrpos()` way is much quicker. But the difference is only ~0.388506 over 1000 calls. – alex Nov 19 '10 at 12:23
  • 25
    While `__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) – Drew Stephens Apr 28 '11 at 17:34
  • 4
    @Drew I guess that depends on what you really want. – alex Apr 28 '11 at 23:17
  • 1
    agreed with @DrewStephens, `SCRIPT_NAME` or `SCRIPT_FILENAME` would work best – SparK Feb 04 '14 at 10:57
  • I agree with @DrewStephens, SCRIPT_NAME or SCRIPT_FILENAME would work best. I am working inside an include file and __FILE__ fails as it returns the literal file and not the script name in this case – Jc Nolan Jun 16 '19 at 18:24
  • @alex I agree with you that using standard library functions are much faster. Although this is my first time seeing this post I caught a mistake in your [codepad](http://codepad.org/fDO0AvHD) that skewed the results shown and I am surprised no one noticed. On line 14 you named the "now" variable with a "1" but left out the "1" on line 22 when you were subtracting it for the $duration1 result. Correct [codepad results](http://codepad.org/maktYcbA) Cheers! – subless May 04 '23 at 06:33
146

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.

SparK
  • 5,181
  • 2
  • 23
  • 32
74

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

pathinfo(__FILE__, PATHINFO_FILENAME);
Angel Politis
  • 10,955
  • 14
  • 48
  • 66
max4ever
  • 11,909
  • 13
  • 77
  • 115
63

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.

Khandad Niazi
  • 2,326
  • 3
  • 25
  • 22
  • which is safer `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 – SparK Jan 29 '14 at 14:56
  • 1
    both have their own impotence, But you can safe your url using different filers, like mysql_real_escape_string, stripslashes etc.. – Khandad Niazi Jan 29 '14 at 15:43
  • 5
    @KhandadNiazi `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`. – katalin_2003 Nov 03 '14 at 19:10
29

This might help:

basename($_SERVER['PHP_SELF'])

it will work even if you are using include.

charan315
  • 291
  • 3
  • 2
27

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>

begoyan
  • 404
  • 5
  • 10
  • 1
    So... SCRIPT_NAME, SCRIPT_FILENAME and PHP_SELF are 3 different things, right? (Why so many vars with same value?! Rasmus was on drugs for sure) – SparK May 19 '16 at 12:31
  • Scenario: `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 – s3c Feb 18 '20 at 06:49
22

alex's answer is correct but you could also do this without regular expressions like so:

str_replace(".php", "", basename($_SERVER["SCRIPT_NAME"]));
user
  • 16,429
  • 28
  • 80
  • 97
  • 6
    This runs the risk of mangling a filename like `hey.php-i-am-a-weird-filename.php`. – alex Nov 19 '10 at 02:08
  • I already thought of that but I figured they were using it for the single page mentioned in the question. You could also check to see if the ".php" is at the end of the string. Not saying your question is wrong but regular espressions can be kind of a pain in the ass and are usually used in scenarios where a much simpler and less resource intensive method could be used. – user Nov 19 '10 at 02:39
  • Shofner I ran some benchmarks and your way runs about twice as quick, but still over 1000 iterations the difference is 0.003231 microseconds. – alex Nov 19 '10 at 12:12
9

you can also use this:

echo $pageName = basename($_SERVER['SCRIPT_NAME']);
Shah Alom
  • 1,031
  • 1
  • 14
  • 26
5

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.

Megachip
  • 359
  • 3
  • 13
5

$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.

JBH
  • 1,823
  • 1
  • 19
  • 30
  • on CLI argV returns a full path. – Martin Feb 14 '22 at 16:19
  • @Martin It appears $argv using CLI does have that problem. According to [php.net](https://www.php.net/manual/en/reserved.variables.argv.php) $argv[0] should return just the script name, but a comment at the bottom of the page suggests (based on correcting its grammar), that the behavior you're seeing has been an issue for years. Thanks for pointing that out. – JBH Feb 16 '22 at 16:40
  • It is yes possible for $argv[ 0 ] to be null. – Bilbo Dec 23 '22 at 17:33
3

Try This

$current_file_name = $_SERVER['PHP_SELF'];
echo $current_file_name;
dipenparmar12
  • 3,042
  • 1
  • 29
  • 39
3

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

Bolli
  • 4,974
  • 6
  • 31
  • 47
3

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.

Mahdyfo
  • 1,155
  • 7
  • 18
  • 1
    It should be clarified that the first calling script is always `[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. – Martin Feb 14 '22 at 16:55
3

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
?>
Eugen
  • 1,356
  • 12
  • 15
2

Try this

$file = basename($_SERVER['PATH_INFO']);//Filename requested
Alvin567
  • 305
  • 2
  • 8
1
$filename = "jquery.js.php";
$ext = pathinfo($filename, PATHINFO_EXTENSION);//will output: php
$file_basename = pathinfo($filename, PATHINFO_FILENAME);//will output: jquery.js
Rahul Gupta
  • 9,775
  • 7
  • 56
  • 69
1

__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
Dariusz Sikorski
  • 4,309
  • 5
  • 27
  • 44
1

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

SparK
  • 5,181
  • 2
  • 23
  • 32
Gendrith
  • 196
  • 1
  • 4
  • 13