December 20th, 2006

How to get / parse the web page file name with PHP

I recently had the need to determine the exact file name of the current web page within a PHP application. It is simple to retrieve the full URL containing the filename, such as http://www.domain.com/example.php using $_SERVER['PHP_SELF'], but I wanted to parse only the 'example.php' part.

I used two string functions to do this, substr and strrpos. Strrpos finds the last occurrence of "/", and substr parses everything after that. Here's the code:


substr($_SERVER['PHP_SELF'], strrpos($_SERVER['PHP_SELF'], "/") + 1)
Share

5 Responses to ' How to get / parse the web page file name with PHP '

Subscribe to comments with RSS or TrackBack to ' How to get / parse the web page file name with PHP '.


  1. on January 2nd, 2007 at 5:21 am

    I could be wrong, but wouldn't $_SERVER['REQUEST_URI'] give you "/example.php" if the URL was "http://www.domain.com/example.php"?
    That seems to be the behavior for me. In that case you could just do:
    substr($_SERVER['REQUEST_URI'], 1)
    which would give you:
    "example.php"
    Again, I could be wrong about this..


  2. on January 2nd, 2007 at 6:12 am

    I should mention that:
    substr($_SERVER['REQUEST_URI'], 1)
    Would give "a/example.php" given "http://www.domain.com/a/example.php"


  3. on January 2nd, 2007 at 6:22 am

    substr($_SERVER['REQUEST_URI'], strrpos($_SERVER['REQUEST_URI'], '/')+1)

    will give "example.php" when the URL is "http://www.domain.com/a/b/c/d/example.php"

  4. Fozzy said,

    on January 17th, 2007 at 5:16 pm

    Just a note… URL's "might" have extra '/' on them…

    http://www.example.com/myfile.php/too/many/slashes

    $_SERVER['PHP_SELF'] will return that full URL and your real file name is not coming before the last slash. However, if you use $_SERVER['SCRIPT_NAME'], you will only get the path up to the filename and any extra whitespace or dots(.) after the filename. The rest of the 'path info' can be taken from PHP with $_SERVER['PATH_INF'], which will be the "/too/many/slashes" part of it all.

    You can test this by doing an…
    echo ''; print_r($_SERVER); echo ''
    and see what server variables PHP will output, and play around with URLs. This can be important for XSS (cross-site scripting) attacks.

    Cheers,
    Fozzy

  5. Fozzy said,

    on January 17th, 2007 at 5:17 pm

    Sorry, It should be $_SERVER['PATH_INFO'], it was a typo.

Leave a reply

*
To prove you're a person (not a spam script), type the security word shown in the picture. Click on the picture to hear an audio file of the word.
Click to hear an audio file of the anti-spam word