1

How do I get just the current file name with PHP?

If I am on URL:

website.com/content/content.php
or
website.com/content/content.php?get=get

I want to simply get:

content.php

With nothing more or less then that. But all I have found returns things like: -"website.com/content/content.php"
-"/content/content.php"

Thanks in advance.

user2953063
  • 437
  • 2
  • 6
  • 10

4 Answers4

7

Use:

basename($_SERVER['SCRIPT_FILENAME'])

Reference

Pupil
  • 23,834
  • 6
  • 44
  • 66
6

You've probably seen:

$_SERVER['SCRIPT_FILENAME'] // for example: /dir/dir/dir/script.php

or

$_SERVER['PHP_SELF'] // as above but not safe

My favorite:

basename(__FILE__) // script.php

basename() function returns you only filename of script without any dir. You can as well use it with any other input:

basename($_SERVER['SCRIPT_FILENAME']) // outputs: script.php

I prefer to avoid $_SERVER variables so I use magic variable __FILE__

Muhammad Hassaan
  • 7,296
  • 6
  • 30
  • 50
Forien
  • 2,712
  • 2
  • 13
  • 30
5

used the basename

echo basename(__FILE__); //it's return content.php

http://php.net/manual/en/function.basename.php

<?php
echo "1) ".basename("/content/content.php", "").PHP_EOL;
echo "2) ".basename("/content/content.php", ".php").PHP_EOL;
echo "3) ".basename("/content/content").PHP_EOL;
echo "4) ".basename("/content/").PHP_EOL;
echo "5) ".basename(".").PHP_EOL;
echo "6) ".basename("/");
?>
//output 
1) content.php
2) content
3) content
4) content
5) .
6) 
Ankur Bhadania
  • 4,123
  • 1
  • 23
  • 38
-1

or you can use

echo __FILE__;

this is a magic constant (click for more info)

This will return the value with .php like you want. Check it!

Ares Draguna
  • 1,641
  • 2
  • 16
  • 32
  • this also returns: For me this returns: C:/Wamp/www/folder/folder/content.php – user2953063 Dec 04 '14 at 14:07
  • `__FILE__` itself returns full path from root to current file. Check my answer [link](http://stackoverflow.com/a/27296059/3720605) – Forien Dec 04 '14 at 14:18