Avatar ·

How to get file extension in PHP? Reliable methods and pitfalls

Hello everyone! I'm a beginner PHP developer and I've encountered what seems like a simple task: I need to get the file extension from its name. I have a variable, for example, `$filename = "document.pdf"` or `$path = "/var/www/uploads/image.jpg"`. I need to extract "pdf" or "jpg". I tried the simplest method — explode with a dot: ```php $filename = "document.pdf"; $parts = explode('.', $filename); $ext = end($parts); echo $ext; // pdf ``` But immediately problems arose. First, what if the filename has multiple dots, for example, `my.file.name.txt`? My code will output "txt", which seems correct, but what if that's not what's needed? Second, what if it's a full path rather than just a name? For example, `/home/user/file.tar.gz` — explode will split everything by slashes and dots, and the result may not be what's expected.