PHP Code

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 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)


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

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

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

    will give "example.php" when the URL is ""

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

    $_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.


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

Leave a Reply

Your email address will not be published. Required fields are marked *

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.
Anti-spam image