How to get the filename from a remote URL

This is another quite simple article. The idea is to find the filename of a remote URL, so if you have the address “http://www.example.com/files/movie.avi” stored in a variable, you want to strip out everything and just be left with “movie.avi”. This is quite a trivial problem, but it is useful to know about this function for doing it.

The way we’ll find out the filename is using PHP’s basename() function, which takes the path to a local file, or the address of a remote file, and returns the filename associated with it. Note that this doesn’t check that the file exists - it just examines the name.

So, for example:

<?
echo basename('http://example.com/files/movie.avi'). '<br />';  // returns "movie.avi" (remote file)
echo basename('/home/user/password.txt'). '<br />';   // returns "password.txt" (local file)
echo basename('http://example.com/') . '<br />';   // returns "example.com"
echo basename('http://example.com/files/page.php?admin=true');  // returns "page.php?admin=true"
?>

The last example above shows that the function doesn’t strip out things such as the query string, so if you want to do that, you’ll have to do it yourself. One possible way is to use the explode() function on the string returned by basename():

<?
$page_parts = explode("?",basename('http://example.com/files/page.php?admin=true'));
echo $page_parts[0];
// returns "page.php"
?>

For more information, please check out the PHP manual entries for basename and explode, or leave a comment!

0 Responses to “How to get the filename from a remote URL”


  1. No Comments

Leave a Reply

You must login to post a comment.