PHP- Getting The Filename From A URL

Image frame
PHP- Getting The Filename From A URL
Maruf
Mar 27th, 2009
Maruf scribbled this post.

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.


Filed away: PHP

comments

Image frame
1

Other method

$base = basename($_SERVER['REQUEST_URI'], “.php”);

rodrigo
May 31st, 2009
Image frame
2

you are a god-send!

Jacob
Jul 17th, 2010

feel free to leave a scribble

Name:
Email:
gravatar
Want an image next to your comments?
visit gravatar.com
Message:
Get a free quote