Derfder
Derfder

Reputation: 3324

Get a filename from a string in PHP

I have this strings saved in my mysql database in format like:

/uploads/attachments/18/105/WordPress_3_Cookbook.pdf

Now, I need to get only the file name.

I guess I need some function in PHP that check the string from the backwards and get everything to the first slash.

How to write such thing?

Upvotes: 1

Views: 921

Answers (2)

Adrian Chelu
Adrian Chelu

Reputation: 1

1.If you don't want to type all the link path inside the "basename()" function, you can use:

$_SERVER['REQUEST_URI']

this will return the whole path - (example below)

"/uploads/attachments/18/105/WordPress_3_Cookbook.pdf"

2.THEN make use of the 'baseline()' function like this:

      echo basename($_SERVER['REQUEST_URI']);

and will return the desired file name as a string.

      // the output will be : WordPress_3_Cookbook.pdf 

Upvotes: 0

Hardik
Hardik

Reputation: 1411

You can use basename() this way

$filename = basename("/uploads/attachments/18/105/WordPress_3_Cookbook.pdf");

Upvotes: 11

Related Questions