- filetype
- Errors/Exceptions
- Examples
- Notes
- See Also
- User Contributed Notes 6 notes
- pathinfo
- Parameters
- Return Values
- Examples
- See Also
- How to Get a File Extension in PHP
- Explode a File Variable
- Find the Last Occurrence of ‘.’
- Use strrpos
- Use preg_replace
- Use pathinfo
- Как узнать расширение файла средствами PHP
- Узнать расширение файла используя PHP функции
- Узнать расширение файла используя класс PHP SplFileInfo
- Как определить расширение файла в PHP
filetype
Returns the type of the file. Possible values are fifo, char, dir, block, link, file, socket and unknown.
Returns false if an error occurs. filetype() will also produce an E_NOTICE message if the stat call fails or if the file type is unknown.
Errors/Exceptions
Upon failure, an E_WARNING is emitted.
Examples
Example #1 filetype() example
echo filetype ( ‘/etc/passwd’ );
echo «\n» ;
echo filetype ( ‘/etc/’ );
The above example will output:
Notes
Note: The results of this function are cached. See clearstatcache() for more details.
As of PHP 5.0.0, this function can also be used with some URL wrappers. Refer to Supported Protocols and Wrappers to determine which wrappers support stat() family of functionality.
See Also
- is_dir() — Tells whether the filename is a directory
- is_file() — Tells whether the filename is a regular file
- is_link() — Tells whether the filename is a symbolic link
- file_exists() — Checks whether a file or directory exists
- mime_content_type() — Detect MIME Content-type for a file
- pathinfo() — Returns information about a file path
- stat() — Gives information about a file
User Contributed Notes 6 notes
There are 7 values that can be returned. Here is a list of them and what each one means
block: block special device
char: character special device
unknown: unknown file type
filetype() does not work for files >=2GB on x86 Linux. You can use stat as a workarround:
Note that stat returns diffenerent strings («regular file»,»directory». )
I use the CLI version of PHP on Windows Vista. Here’s how to determine if a file is marked «hidden» by NTFS:
function is_hidden_file ( $fn )
$attr = trim ( exec ( ‘FOR %A IN («‘ . $fn . ‘») DO @ECHO %~aA’ ));
if( $attr [ 3 ] === ‘h’ )
return true ;
This should work on any Windows OS that provides DOS shell commands.
Putting @ in front of the filetype() function does not prevent it from raising a warning (Lstat failed), if E_WARNING is enabled on your error_reporting.
The most common cause of filetype() raising this warning and not showing a filetype() in the output (it actually returns NULL) is, if you happened to pass just the ‘Dir or File Name’ and not the complete «Absolute or Relative Path» to that ‘file or Dir’. It may still read that file and return its filetype as «file» but for Dir’s it shows warning and outputs NULL.
eg:
$pathToFile = ‘/var/www’;
$file = ‘test.php’;
$dir = ‘somedir’;
Output for filetype($file) will be returned as ‘file’ and possibly without any warning, but for filetype($dir), it will return NULL with the warning «Lstat failed», unless you pass a complete path to that dir, i.e. filetype($pathToFile.’/’.$dir).
This happened to me and found this solution after a lot of trial and error. Thought, it might help someone.
Note there is a bug when using filetype with for example Japanese filenames :
https://bugs.php.net/bug.php?id=64699
The whole PHP interpreter comes crashing down without anyway to avoid it or capture an exception.
echo «Zum testen müssen tatsächlich existente Namen verwendet werden.
» ;
echo «Pfad und Dateiname müssen getrennt eingetragen und durch einen Punkt verbunden sein.
» ;
echo «Example: [filetype(\»../dir/u_dir/\».\»temp.jpg\»)] liefert -> file
» ;
?>
pathinfo
pathinfo() returns information about path : either an associative array or a string, depending on flags .
Note:
For information on retrieving the current path info, read the section on predefined reserved variables.
Note:
pathinfo() operates naively on the input string, and is not aware of the actual filesystem, or path components such as » .. «.
Note:
On Windows systems only, the \ character will be interpreted as a directory separator. On other systems it will be treated like any other character.
pathinfo() is locale aware, so for it to parse a path containing multibyte characters correctly, the matching locale must be set using the setlocale() function.
Parameters
If present, specifies a specific element to be returned; one of PATHINFO_DIRNAME , PATHINFO_BASENAME , PATHINFO_EXTENSION or PATHINFO_FILENAME .
If flags is not specified, returns all available elements.
Return Values
If the flags parameter is not passed, an associative array containing the following elements is returned: dirname , basename , extension (if any), and filename .
Note:
If the path has more than one extension, PATHINFO_EXTENSION returns only the last one and PATHINFO_FILENAME only strips the last one. (see first example below).
Note:
If the path does not have an extension, no extension element will be returned (see second example below).
Note:
If the basename of the path starts with a dot, the following characters are interpreted as extension , and the filename is empty (see third example below).
If flags is present, returns a string containing the requested element.
Examples
Example #1 pathinfo() Example
$path_parts = pathinfo ( ‘/www/htdocs/inc/lib.inc.php’ );
?php
echo $path_parts [ ‘dirname’ ], «\n» ;
echo $path_parts [ ‘basename’ ], «\n» ;
echo $path_parts [ ‘extension’ ], «\n» ;
echo $path_parts [ ‘filename’ ], «\n» ;
?>
The above example will output:
/www/htdocs/inc lib.inc.php php lib.inc
Example #2 pathinfo() example showing difference between null and no extension
$path_parts = pathinfo ( ‘/path/emptyextension.’ );
var_dump ( $path_parts [ ‘extension’ ]);
?php
$path_parts = pathinfo ( ‘/path/noextension’ );
var_dump ( $path_parts [ ‘extension’ ]);
?>
The above example will output something similar to:
string(0) "" Notice: Undefined index: extension in test.php on line 6 NULL
Example #3 pathinfo() example for a dot-file
The above example will output something similar to:
Array ( [dirname] => /some/path [basename] => .test [extension] => test [filename] => )
Example #4 pathinfo() example with array dereferencing
The flags parameter is not a bitmask. Only a single value may be provided. To select only a limited set of parsed values, use array destructuring like so:
[ ‘basename’ => $basename , ‘dirname’ => $dirname ] = pathinfo ( ‘/www/htdocs/inc/lib.inc.php’ );?php
var_dump ( $basename , $dirname );
?>
The above example will output something similar to:
string(11) "lib.inc.php" string(15) "/www/htdocs/inc"
See Also
- dirname() — Returns a parent directory’s path
- basename() — Returns trailing name component of path
- parse_url() — Parse a URL and return its components
- realpath() — Returns canonicalized absolute pathname
How to Get a File Extension in PHP
In PHP, there exist various ways of getting a file extension. In our tutorial, we have chosen the 5 best ways that will help you to get a file extension straightforwardly.
Go ahead and choose the one that matches your project better.
Explode a File Variable
The first way is exploding a file variable and getting the last element of the array. That will be a file extension. Here is how you can do it:
$fileName = 'banner.jpg'; $fileNameParts = explode('.', $fileName); $ext = end($fileNameParts); echo $ext; ?>
Find the Last Occurrence of ‘.’
In the framework of the second approach, we recommend detecting the last occurrence of ‘.’, which will return a ‘.jpg’ . Afterwards, you need to remove the first character of a string using substr. As a result, the exact file extension ‘.jpg’ will be returned.
$fileName = 'banner.jpg'; $ext = substr(strrchr($fileName, '.'), 1); echo $ext; ?>
Use strrpos
The next way is to use strrpos for detecting the position of the last occurrence of ‘.’ inside a file name, incrementing that position by 1 so that it explodes a string from (.).
The example is shown below:
$fileName = 'banner.jpg'; $ext = substr($fileName, strrpos($fileName, '.') + 1); echo $ext; ?>
Use preg_replace
In the framework of this approach, you should apply a regular expression reach and replacement.
$fileName = 'banner.jpg'; $ext = preg_replace('/^.*\.([^.]+)$/D', '$1', $fileName); echo $ext; ?>
Use pathinfo
And, the final approach that we recommend is to use the PHP pathinfo() function. It is aimed at returning information about the file. In case the second optional parameter is not passed, an associative array will be returned. It will include the dirname, extension, basename, and filename. Once the second parameter is passed, then specific information will be returned.
$fileName = 'banner.jpg'; $ext = pathinfo($fileName, PATHINFO_EXTENSION); echo $ext; ?>
So, after learning about all the possible ways described above, you are free to choose the best one for you. In our opinion, the simplest, yet the most efficient way among all these options is the pathinfo() function.
Как узнать расширение файла средствами PHP
В данной заметке я покажу несколько способов на PHP, которые помогут узнать расширение файла. Все способы рабочие, а какой из них использовать на практике, решать вам исходя из поставленных задач.
$uploadImage = $_FILES['image']; $uploadImageName = trim(strip_tags($uploadImage['name'])); $uploadImageTmpName = trim(strip_tags($uploadImage['tmp_name'])); // Способ #1 $extension = pathinfo($uploadImageName, PATHINFO_EXTENSION); // Способ #2 $extension = pathinfo(parse_url($uploadImageName, PHP_URL_PATH), PATHINFO_EXTENSION); // Способ #3 $extension = substr($uploadImageName, strrpos($uploadImageName, '.') + 1); // Способ #4 $extension = substr(strrchr($uploadImageName,'.'), 1);
Узнать расширение файла используя PHP функции
// Способ #1 function getExtension($filename) < return preg_replace('/^.*\.(.*)$/U', '$1', $filename); >// Способ #2 function getExtension($filename) < return preg_match('/\.(.*)$/U', $filename, $matches) ? $matches[1]: ''; >// Способ #3 function get_file_extension($file_path) < $basename = basename($file_path); // получение имени файла if ( strrpos($basename, '.')!==false ) < // проверка на наличии в имени файла символа точки // вырезаем часть строки после последнего символа точки в имени файла $file_extension = substr($basename, strrpos($basename, '.') + 1); >else < // в случае отсутствия символа точки в имени файла возвращаем false $file_extension = false; >return $file_extension; >
Узнать расширение файла используя класс PHP SplFileInfo
$file = new SplFileInfo($uploadImageName); $extension = $file->getExtension();
Как определить расширение файла в PHP
Задача определения расширения возникает в разработке достаточно часто – здесь и загрузка файлов на сервер, и анализ имеющихся файлов, и поиск файла. В работе с файлами на сервере, есть так же частое решение сохранения файла не с исходным именем, а назначение в качестве имени файла текущего значения TIMESTAMP сервера. Решений у этой задачи существует немало для разных языков программирования. Хотя некоторые решения, в первую очередь, приходящие на ум, иногда приходится дорабатывать из-за того разнообразия имен файлов которые только могут быть. Для файла с именем «myfile.txt» можно смело предложить разбить строку на части разделенные точкой и взять последнюю. Но что делать с файлами «my.file.txt» или в случае, если расширение не указано «myfile»?
В этой статье, рассмотрим такие решения.
Для удобства имя файл зададим в строковой переменной:
$filename = 'myfile.txt'; // другие варианты имени файла $filename = 'file'; // не указано расширение $filename = 'my.file.txt'; // точка в имени файла $filename = 'dir/myfile.txt'; // имя файла с указанием директории ?>
Самое простое и удобное, на мой взгляд, решение использовать с, которая вернет ассоциированный массив, содержащий сведения полном имени, расширении и директории файла. После этого остается только вывести необходимый элемент массива.
function get_file_extension($filename) < $file_info = pathinfo($filename); return $file_info['extension']; >echo get_file_extension($filename); ?>
Чтобы не делать собственную функцию можно упросить код, указав в качестве второго параметра значение PATHINFO_EXTENSION. В этом случае функция вернет не весь массив, а только значение расширения.
echo pathinfo($filename, PATHINFO_EXTENSION); ?>
Оба варианта корректно вернут значение расширения «txt», кроме случая, где расширение не указано. Там, где расширения нет, будет возвращена пустая строка.
Это решение доступно для PHP, начиная с версии 4.0.3.
Если по причине версии PHP или какой-либо другой причине это решение не доступно, можно использовать традиционное решение – разбивку строки имени файла на части между точками, считая, что последний участок и будет расширением.
function get_file_extension($filename) < return end(explode(".", $filename)); >echo get_file_extension($filename); ?>
Здесь, функция explode() разбивает строку на массив из символов, разделенных точками, а функция end() возвращает последний элемент полученного массива.
В этом примере, если расширение не задано явно, т.е. точки в имени файла нет, будет возвращено исходное имя файла. В случае, если расширение есть, оно будет получено корректно.