How do I get a file extension in PHP?

前端 未结 28 2326
一向
一向 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条回答
  •  旧时难觅i
    2020-11-21 23:04

    E-satis's response is the correct way to determine the file extension.

    Alternatively, instead of relying on a files extension, you could use the fileinfo to determine the files MIME type.

    Here's a simplified example of processing an image uploaded by a user:

    // Code assumes necessary extensions are installed and a successful file upload has already occurred
    
    // Create a FileInfo object
    $finfo = new FileInfo(null, '/path/to/magic/file');
    
    // Determine the MIME type of the uploaded file
    switch ($finfo->file($_FILES['image']['tmp_name'], FILEINFO_MIME)) {        
        case 'image/jpg':
            $im = imagecreatefromjpeg($_FILES['image']['tmp_name']);
        break;
    
        case 'image/png':
            $im = imagecreatefrompng($_FILES['image']['tmp_name']);
        break;
    
        case 'image/gif':
            $im = imagecreatefromgif($_FILES['image']['tmp_name']);
        break;
    }
    

提交回复
热议问题