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

  1. 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. I should mention that:
    substr($_SERVER['REQUEST_URI'], 1)
    Would give "a/example.php" given "http://www.domain.com/a/example.php"

  3. 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. 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. 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