-1

I am trying to get the file name from URL and here I use basename to get the file name but it not works.

basename('https://test-assets.amazonaws.com/live%2Ftestsamantha-9-bucket%2Ff132eb33-f403-4881-80e2-de1cc3bdb43a.jpg');

Result is

live%2Ftestsamantha-9-bucket%2Ff132eb33-f403-4881-80e2-de1cc3bdb43a.jpg

How do I get

f132eb33-f403-4881-80e2-de1cc3bdb43a.jpg

2 Answers2

3

You take the url just as you did, use urldecode on it, so slashes are plain slashes and nothing encoded. Then all you have to do, is explode by slash and take the last element of the created array. Voila.

$url = urldecode(basename('https://test-assets.amazonaws.com/live%2Ftestsamantha-9-bucket%2Ff132eb33-f403-4881-80e2-de1cc3bdb43a.jpg'));
$parts = explode('/', $url);

print end($parts); // Prints 'f132eb33-f403-4881-80e2-de1cc3bdb43a.jpg'

Or better, do it like the other poster did, its less code and he is right. While my solution works too, its more than needed.

Manuel Mannhardt
  • 2,191
  • 1
  • 17
  • 23
2

You need to decode the url first using the urldecode method:

basename(urldecode('https://test-assets.amazonaws.com/live%2Ftestsamantha-9-bucket%2Ff132eb33-f403-4881-80e2-de1cc3bdb43a.jpg'));

The urldecode method converts the url to https://test-assets.amazonaws.com/live/testsamantha-9-bucket/f132eb33-f403-4881-80e2-de1cc3bdb43a.jpg and then the basename method works properly.

Claudio
  • 5,078
  • 1
  • 22
  • 33