PHP : Strip filename from a URL

Sat, Apr 26, 2008

PHP

Using PHP, you might need to strip the path from a URL, leaving behind just the filename at the end of the URL. You can achieve this with a regular expression pattern of course, but I have a much simpler solution. See the example code below.

$url = "http://www.domain.com/path/to/file/filename.php";
$filename = basename($url);
echo $filename; //filename.php

And that’s all there is to it. I hope that you found this useful.

, , , , , ,
scriptlancebannerpng

This post was written by:

- who has written 71 posts on Lost-In-Code.

I (Antonie Potgieter) am a software engineer/web developer located in South Africa. My full-time work is the management of Tribulant Software and the development of its software packages.

Contact the author

11 Comments For This Post

  1. shonhloi Says:

    thank u, very useful and classic

  2. Doug Says:

    that doesn’t work if you have url variables.

  3. kosmofilo Says:

    Thank you. Such functions are really nice. I’d need a piece of garbage to do that with Javascript.

  4. humor Says:

    Great news, I want thank to admin coz’ i have found a lot useful info. Keep it going! :) . Best wishes :)

  5. Randy Says:

    Hello,

    I am looking for a program to strip the url from images so it leaves just the image name. Would this work for that purpose?

  6. plr store Says:

    awesome, it works for getting images from urls as well,
    i thought basename only worked for paths

  7. Ben Rolfe Says:

    @plr store: basename will work on any string – files, folders, or just random junk – it doesn’t actually understand anything about the filesystem, it’s just looking for slashes.

  8. Bigben Says:

    Cool, but it’s not working if you have some parameters in the URL!!

  9. Bigben Says:

    OK, I tried this:

    $filename = basename($url);
    $parts=explode(“?”,$filename);
    $filename = $parts[0];
    echo $filename;

    And it works!!

  10. vamshi Says:

    thanks a lot

  11. AndreG Says:

    Thank you!
    Brilliant and simple.

Leave a Reply