How do I get a file extension in PHP?

前端 未结 28 2258
一向
一向 2020-11-21 22:45

This is a question you can read everywhere on the web with various answers:

$ext = end(explode(\'.\', $filename));
$ext = substr(strrchr($filename, \'.\'), 1         


        
28条回答
  •  醉话见心
    2020-11-21 23:21

    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()
    

提交回复
热议问题