This is a question you can read everywhere on the web with various answers:
$ext = end(explode(\'.\', $filename));
$ext = substr(strrchr($filename, \'.\'), 1
I found that the pathinfo()
and SplFileInfo
solutions works well for standard files on the local file system, but you can run into difficulties if you're working with remote files as URLs for valid images may have a #
(fragment identifiers) and/or ?
(query parameters) at the end of the URL, which both those solutions will (incorrect) treat as part of the file extension.
I found this was a reliable way to use pathinfo()
on a URL after first parsing it to strip out the unnecessary clutter after the file extension:
$url_components = parse_url($url); // First parse the URL
$url_path = $url_components['path']; // Then get the path component
$ext = pathinfo($url_path, PATHINFO_EXTENSION); // Then use pathinfo()