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