Web Design Blog

This is where we store some of our Web Development thoughts, tips and tricks, just because we like to share.

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.

27 Mar 2009 / 6 Comments / PHP Scripts, Tips & Tricks / by Maruf

6 Comments

  1. rodrigo
    31/05/2009
    1

    Other method

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

  2. Jacob
    17/07/2010
    2

    you are a god-send!

  3. 03/01/2011
    3

    Thank you for this!

  4. 27/04/2011
    4

    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’

  5. 03/08/2011
    5

    Cool, but it’s not working if you have some parameters in the URL!!

  6. 16/09/2011
    6

    strstr(basename($_SERVER['REQUEST_URI']), ‘.php’, true);
    gets any thing before the .php file extension

    works good in php 4-5

Leave a Reply

© 2012 BrightCherry :)