PHP- Getting The Filename From A URL
Someone emailed me, asking me how to get the filename from a URL using PHP. It’s pretty easy, but I thought i’d jot it down for everyone, just in case other people want the same result.
Example
Ok, so we want the filename for the following page:
http://www.anydomain.co.uk/page/grab.php
We want to grab the filename, which is grab.php
The following code will do that for you:
1 | $basename = basename($_SERVER['REQUEST_URI']); |
If you want to remove the .php, a simple string replace function will do:
1 | $basename = str_replace(".php","",basename($_SERVER['REQUEST_URI'])); |
And that’s it.


brightcherry.co.uk
Other method
$base = basename($_SERVER['REQUEST_URI'], “.php”);
you are a god-send!
Thank you for this!
Note that if you do not parse $_SERVER['REQUEST_URI'], but whole URL like http://exzmple.com/index.php?page=about basename($URL, ‘.php’) returns ‘index.php?page=about’
Cool, but it’s not working if you have some parameters in the URL!!
strstr(basename($_SERVER['REQUEST_URI']), ‘.php’, true);
gets any thing before the .php file extension
works good in php 4-5