¿Cómo obtener (extraer) una extensión de archivo en PHP?


Esta es una pregunta que puedes leer en todas partes en la web con varias respuestas :

$ext = end(explode('.', $filename));
$ext = substr(strrchr($filename, '.'), 1);
$ext = substr($filename, strrpos($filename, '.') + 1);
$ext = preg_replace('/^.*\.([^.]+)$/D', '$1', $filename);

$exts = split("[/\\.]", $filename);
$n    = count($exts)-1;
$ext  = $exts[$n];

Etc.

Sin embargo, siempre hay "la mejor manera" y debe estar en el Desbordamiento de la pila.

Author: STLDeveloper, 2008-10-06

22 answers

Las personas de otros lenguajes de scripting siempre piensan que el suyo es mejor porque tienen una función incorporada para hacer eso y no PHP (estoy mirando a pythonistas en este momento :-)).

De hecho, existe, pero pocas personas lo saben. Conocer pathinfo():

$ext = pathinfo($filename, PATHINFO_EXTENSION);

Esto es rápido y está integrado. pathinfo() puede darte otra información, como la ruta canónica, dependiendo de la constante que le pases.

Recuerde que si desea ser capaz de tratar con caracteres no ASCII, usted necesidad de establecer la configuración regional primero. Por ejemplo:

setlocale(LC_ALL,'en_US.UTF-8');

También tenga en cuenta que esto no tiene en cuenta el contenido del archivo o el tipo mime, solo obtiene la extensión. Pero es lo que pediste.

Por último, tenga en cuenta que esto solo funciona para una ruta de archivo, no para una ruta de recursos de URL, que se cubren con PARSE_URL.

Disfruta

 1588
Author: e-satis,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-06-20 15:47:29

pathinfo()

$path_info = pathinfo('/foo/bar/baz.bill');

echo $path_info['extension']; // "bill"
 141
Author: Adam Wright,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-07-27 09:43:55

Uso más seguro: PARSE_URL (en lugar de PATHINFO)


Por ejemplo, url es http://example.com/myfolder/sympony.mp3?a=1&b=2#XYZ

PATHINFO devuelve:

$x = pathinfo($url);
$x['dirname']    'http://example.com/myfolder'
$x['basename']   'sympony.mp3?a=1&b=2'         // <------- BAD !!
$x['extension']  'mp3?a=1&b=2'                 // <------- BAD !!
$x['filename']   'sympony'


PARSE_URL devuelve:

$x = parse_url($url);
$x['scheme']   'http'
$x['host']     'example.com'
$x['path']     '/myfolder/sympony.mp3'
$x['query']    'aa=1&bb=2'
$x['fragment'] ''             //<----- this outputs hashtag "XYZ" only in case, when the link containing that hashtag was manually passed to function, because automatically, hashtags are not automatically detectable by PHP

dirname(parse_url($url)['path'])                       /myfolder
basename(parse_url($url))                              sympony.mp3
pathinfo(parse_url($url)['path'], PATHINFO_EXTENSION)  mp3

P. s. Nota, la parte Hashtag de la url (es decir, #smth) no está disponible en la solicitud PHP, pero solo con javascript.


Para ejemplos útiles, vea: Obtenga la URL completa en PHP

 72
Author: T.Todua,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-04-14 09:00:30

También Hay SplFileInfo:

$file = new SplFileInfo($path);
$ext  = $file->getExtension();

A menudo puede escribir mejor código si pasa un objeto de este tipo en lugar de una cadena, su código es más hablando entonces. Desde PHP 5.4 esto es un solo liner:

$ext  = (new SplFileInfo($path))->getExtension();
 51
Author: hakre,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-10-17 10:32:32

La respuesta E-satis es la forma correcta de determinar la extensión del archivo.

Alternativamente, en lugar de confiar en una extensión de archivos, podría usar el fileinfo ( http://us2.php.net/fileinfo ) para determinar el tipo de archivos MIME.

Aquí hay un ejemplo simplificado de procesamiento de una imagen subida por un usuario:

// 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;
}
 19
Author: Toxygene,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-08-17 18:52:55

1) Si está utilizando (PHP 5 >= 5.3.6) puede utilizar SplFileInfo::getExtension - Obtiene la extensión de archivo

Código de ejemplo

<?php

$info = new SplFileInfo('test.png');
var_dump($info->getExtension());

$info = new SplFileInfo('test.tar.gz');
var_dump($info->getExtension());

?>

Esto producirá

string(3) "png"
string(2) "gz"

2) Otra forma de obtener la prórroga si usted está usando (PHP 4 >= 4.0.3, PHP 5) es pathinfo

Código de ejemplo

<?php

$ext = pathinfo('test.png', PATHINFO_EXTENSION);
var_dump($ext);

$ext = pathinfo('test.tar.gz', PATHINFO_EXTENSION);
var_dump($ext);

?>

Esto producirá

string(3) "png"
string(2) "gz"

/ / EDITAR: se ha eliminado un corchete

 12
Author: Subodh Ghulaxe,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-11-25 13:09:14

Siempre y cuando no contenga ruta, también puede usar:

array_pop(explode('.',$fname))

Donde $fname es un nombre del archivo, por ejemplo: my_picture.jpg Y el resultado sería: jpg

 9
Author: Anonymous,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-08-11 12:49:05

A veces es útil no usar pathinfo($path, PATHINFO_EXTENSION), por ejemplo:

$path = '/path/to/file.tar.gz';

echo ltrim(strstr($path, '.'), '.'); // tar.gz
echo pathinfo($path, PATHINFO_EXTENSION); // gz

También tenga en cuenta que pathinfo no puede manejar algunos caracteres no ASCII (por lo general solo los suprime de la salida), en extensiones que por lo general no es un problema, pero no está de más ser consciente de esa advertencia.

 9
Author: Alix Axel,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-11-01 18:11:18

La forma más sencilla de obtener la extensión de archivo en php es usar la función incorporada de php pathinfo.

$file_ext = pathinfo('your_file_name_here', PATHINFO_EXTENSION);
echo ($file_ext); // the out should be extension of file eg:-png, gif, html
 7
Author: Shahbaz,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-05-13 06:44:32
substr($path, strrpos($path, '.') + 1);
 5
Author: Kurt Zhong,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-12-05 11:13:42

Aquí hay un ejemplo, supongamos que fil filename es "example.txt "

$ext = substr($filename,strrpos($filename,'.',-1),strlen($filename));  

Así que ex ext será ".txt "

 4
Author: G. I. Joe,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-02-25 23:22:17

Una solución rápida sería algo como esto.

    //exploding the file based on . operator
    $file_ext = explode('.',$filename);

    //count taken (if more than one . exist; files like abc.fff.2013.pdf
    $file_ext_count=count($file_ext);

    //minus 1 to make the offset correct
    $cnt=$file_ext_count-1;

    // the variable will have a value pdf as per the sample file name mentioned above.

$file_extension= $file_ext[$cnt];
 4
Author: Annabelle,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-05-26 09:29:54

Pathinfo es una matriz. Podemos comprobar nombre del directorio,nombre del archivo, extensión etc

$path_parts = pathinfo('test.png');

echo $path_parts['extension'], "\n";
echo $path_parts['dirname'], "\n";
echo $path_parts['basename'], "\n";
echo $path_parts['filename'], "\n";  
 4
Author: Arshid KV,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-06-03 04:43:04

Puedes probar también esto
(trabajo en php 5.* y 7)

$info = new SplFileInfo('test.zip');
echo $info->getExtension(); // ----- Output -----> zip

Consejo: devuelve una cadena vacía si el archivo no tiene extensión
disfrutarlo ;)

 4
Author: pooya_sabramooz,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-02-12 05:40:13

Esto funcionará

$ext = pathinfo($filename, PATHINFO_EXTENSION);
 3
Author: Deepika Patel,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-01-15 10:12:23

Encontré que las soluciones pathinfo() y SplFileInfo funcionan bien para archivos estándar en el sistema de archivos local, pero puede tener dificultades si está trabajando con archivos remotos, ya que las URL para imágenes válidas pueden tener un # (identificadores de fragmentos) y/o ? (parámetros de consulta) al final de la URL, que ambas soluciones tratarán (incorrectamente) como parte de la extensión del archivo.

Encontré que esta era una forma confiable de usar pathinfo() en una URL después de analizarla primero para eliminar lo innecesario clutter después de la extensión de archivo:

$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()
 3
Author: Jonathan Ellis,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-01-20 20:40:36

Puedes probar también esto:

 pathinfo(basename( $_FILES["fileToUpload"]["name"]),PATHINFO_EXTENSION)
 2
Author: smile 22121,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-05-24 09:53:55

¿por Qué no usar substr($path, strrpos($path,'.')+1); ? Es el método más rápido de todos comparar. @ Kurt Zhong ya respondió.

Vamos a comprobar el resultado comparativo aquí: https://eval.in/661574

 2
Author: Abbas,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-10-17 05:09:51

Puede obtener toda la extensión de archivo en una carpeta particular y hacer la operación con extensión de archivo específica

<?php
    $files=glob("abc/*.*");//abc is folder all files inside folder
    //print_r($files);
    //echo count($files);
    for($i=0;$i<count($files);$i++):
        $extension = pathinfo($files[$i], PATHINFO_EXTENSION);
        $ext[]=$extension;
        //do operation for perticular extenstion type
        if($extension=='html'){
            //do operation
        }
    endfor;
    print_r($ext);
?>
 1
Author: Samir Karmacharya,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-05-04 05:35:14

Si está buscando velocidad (como en un enrutador), probablemente no quiera tokenizar todo. Muchas otras respuestas fallarán con /root/my.folder/my.css

ltrim(strrchr($PATH, '.'),'.');
 1
Author: Ray Foss,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-09-09 13:54:18

Aunque la "mejor manera" es discutible, creo que esta es la mejor manera por algunas razones:

function getExt($path)
{
    $basename = basename($path);
    return substr($basename, strlen(explode('.', $basename)[0]) + 1);
}
  1. Funciona con múltiples partes a una extensión, por ejemplo tar.gz
  2. Código corto y eficiente
  3. Funciona con un nombre de archivo y una ruta completa
 1
Author: Dan Bray,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-08-05 15:33:57

Use

str_replace('.', '', strrchr($file_name, '.'))

Para una recuperación rápida de la extensión (si está seguro de que su nombre de archivo tiene uno).

 -1
Author: AlexB,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-11-28 12:05:26