Pregunta

I have an image file name without extension (lets assume it is image_file_name - NOTE IT IS MISSING THE EXTENSION) and I also know the file type (lets assume the file type is image/jpeg). Now is there a php function that returns the file extension given its type? As explained in the following pseudo code:

$extension = get_extension('image/jpeg'); // Will return 'jpg'

$file_name = 'image_file_name' . '.' . $extension; // Will result in $file_name = image_file_name.jpg

Please note that the image above was only an example, the file name could be of any file type, such as a web page file name or anything else. and the extension could be anything as well, it could be html, css ...etc.

Is it possible to do the above? And how?

¿Fue útil?

Solución

$ext = substr(image_type_to_extension(exif_imagetype('dev.png')), 1); //example png

This will give you the extension correctly and is more reliable than $_FILE['image']['type'].

Otros consejos

You can use finfo to perform mime-magic to determine the file type.

 $finfo = finfo_open(FILEINFO_MIME, "/path/to/mimiemagic.file");
 $res = $finfo->file($filename);
 list($type, $encoding) = explode(";", $res);
 $typeToExt = array(
     "image/jpeg"=>"jpg",
     "image/png"=>"png",
     "text/html"=>"html",
     "text/plain"=>"txt",
     "audio/mpeg"=>"mp3",
     "video/mpeg"=>"mpg"
 );

 $ext = $typeToExt[$type];

You can use FILEINFO_MIME directly to determine MIME type and then use a switch case to add extension. There is this mime_content_type(), but it seems deprecated.

$finfo = new FileInfo(null, 'image_file_name');

// Determine the MIME type of the uploaded file
switch ($finfo->file($_FILES['image']['tmp_name'], FILEINFO_MIME) {
    case 'image/jpg':
        $extension = 'jpg'
        $file_name = 'image_file_name' . '.' . $extension;
    break;

    case 'image/png':
        $extension = 'png'
        $file_name = 'image_file_name' . '.' . $extension;
    break;

    case 'image/gif':
        $extension = 'gif'
        $file_name = 'image_file_name' . '.' . $extension;
    break;
}

For more extensions, keep adding cases to switch.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top