131

I've a file called demo.php where I don't have any GET variables in the URL, so if I want to hide a button if am on this page I can't use something like this:

if($_GET['name'] == 'value') {
  //Hide
} else {
  //show
}

So I want something like

$filename = //get file name
if($filename == 'file_name.php') {
  //Hide
} else {
  //show
}

I don't want to declare unnecessary GET variables just for doing this...

Samuel Liew
  • 76,741
  • 107
  • 159
  • 260
Random Guy
  • 2,878
  • 5
  • 20
  • 32

3 Answers3

347

You can use basename() and $_SERVER['PHP_SELF'] to get current page file name

echo basename($_SERVER['PHP_SELF']); /* Returns The Current PHP File Name */
Mr. Alien
  • 153,751
  • 34
  • 298
  • 278
  • 5
    what if url is `abc.php?blah=demo` or `abc.php\a\b?` because I just need abc,php – Random Guy Oct 23 '12 at 14:45
  • 11
    you'll get `abc.php` :) – Mr. Alien Oct 23 '12 at 14:46
  • 23
    Also...You can replace the `.php` extension and hyphens `ucwords( str_ireplace(array('-', '.php'), array(' ', ''), basename($_SERVER['PHP_SELF']) ) )` and Capitalize Words with `ucwords` or first letter using `ucfirst`. Maybe somebody will need this... – Andrei Surdu Sep 06 '13 at 11:34
  • 18
    If you do not want the `.php` extension you may use `basename($_SERVER['PHP_SELF'],'.php')` – Adam Feb 15 '17 at 09:47
  • 1
    if you do not want the file extension, you can also use `pathinfo(basename($_SERVER['PHP_SELF']), PATHINFO_FILENAME);` – ofri cofri Aug 18 '20 at 22:26
31

$_SERVER["PHP_SELF"]; will give you the current filename and its path, but basename(__FILE__) should give you the filename that it is called from.

So

if(basename(__FILE__) == 'file_name.php') {
  //Hide
} else {
  //show
}

should do it.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Amykate
  • 485
  • 5
  • 8
11

In your case you can use __FILE__ variable !
It should help.
It is one of predefined.
Read more about predefined constants in PHP http://php.net/manual/en/language.constants.predefined.php

Bogdan Burym
  • 5,482
  • 2
  • 27
  • 46