Get file infos php
- Different ways to write a PHP code
- How to write comments in PHP ?
- Introduction to Codeignitor (PHP)
- How to echo HTML in PHP ?
- Error handling in PHP
- How to show All Errors in PHP ?
- How to Start and Stop a Timer in PHP ?
- How to create default function parameter in PHP?
- How to check if mod_rewrite is enabled in PHP ?
- Web Scraping in PHP Using Simple HTML DOM Parser
- How to pass form variables from one page to other page in PHP ?
- How to display logged in user information in PHP ?
- How to find out where a function is defined using PHP ?
- How to Get $_POST from multiple check-boxes ?
- How to Secure hash and salt for PHP passwords ?
- Program to Insert new item in array on any position in PHP
- PHP append one array to another
- How to delete an Element From an Array in PHP ?
- How to print all the values of an array in PHP ?
- How to perform Array Delete by Value Not Key in PHP ?
- Removing Array Element and Re-Indexing in PHP
- How to count all array elements in PHP ?
- How to insert an item at the beginning of an array in PHP ?
- PHP Check if two arrays contain same elements
- Merge two arrays keeping original keys in PHP
- PHP program to find the maximum and the minimum in array
- How to check a key exists in an array in PHP ?
- PHP | Second most frequent element in an array
- Sort array of objects by object fields in PHP
- PHP | Sort array of strings in natural and standard orders
- How to pass PHP Variables by reference ?
- How to format Phone Numbers in PHP ?
- How to use php serialize() and unserialize() Function
- Implementing callback in PHP
- PHP | Merging two or more arrays using array_merge()
- PHP program to print an arithmetic progression series using inbuilt functions
- How to prevent SQL Injection in PHP ?
- How to extract the user name from the email ID using PHP ?
- How to count rows in MySQL table in PHP ?
- How to parse a CSV File in PHP ?
- How to generate simple random password from a given string using PHP ?
- How to upload images in MySQL using PHP PDO ?
- How to check foreach Loop Key Value in PHP ?
- How to properly Format a Number With Leading Zeros in PHP ?
- How to get a File Extension in PHP ?
- How to get the current Date and Time in PHP ?
- PHP program to change date format
- How to convert DateTime to String using PHP ?
- How to get Time Difference in Minutes in PHP ?
- Return all dates between two dates in an array in PHP
- Sort an array of dates in PHP
- How to get the time of the last modification of the current page in PHP?
- How to convert a Date into Timestamp using PHP ?
- How to add 24 hours to a unix timestamp in php?
- Sort a multidimensional array by date element in PHP
- Convert timestamp to readable date/time in PHP
- PHP | Number of week days between two dates
- PHP | Converting string to Date and DateTime
- How to get last day of a month from date in PHP ?
- PHP | Change strings in an array to uppercase
- How to convert first character of all the words uppercase using PHP ?
- How to get the last character of a string in PHP ?
- How to convert uppercase string to lowercase using PHP ?
- How to extract Numbers From a String in PHP ?
- How to replace String in PHP ?
- How to Encrypt and Decrypt a PHP String ?
- How to display string values within a table using PHP ?
- How to write Multi-Line Strings in PHP ?
- How to check if a String Contains a Substring in PHP ?
- How to append a string in PHP ?
- How to remove white spaces only beginning/end of a string using PHP ?
- How to Remove Special Character from String in PHP ?
- How to create a string by joining the array elements using PHP ?
- How to prepend a string in PHP ?
Fileinfo Functions
The results of this function seem to be of dubious quality.
eg
1) a Word doc returns:
‘application/msword application/msword’
. ok not too bad, but why does it come back twice?
3) a text doc that starts with the letters ‘GIF’ comes back as:
‘image/gif’
(just like in DanielWalker’s example for the unix ‘file’ command)
I had better results using the PEAR ‘MIME_Type’ package. It gave proper answers for 1 & 3 and identified the PHP file as ‘text/plain’ which is probably better than a false match for C++
Both finfo_file and MIME_Type correctly identified my other two test files which were a windows exe renamed with .doc extension, and a PDF also renamed with .doc extension.
/**
* @var str => $file = caminho para o arquivo (ABSOLUTO OU RELATIVO)
* @var arr => $file_info = array contendo as informações obtidas do arquivo informado
*/
private $file ;
private $file_info ;
/**
* @param str => $file = caminho para o arquivo (ABSOLUTO OU RELATIVO)
*/
public function get_file ( string $file ) clearstatcache ();
$file = str_replace (array( ‘/’ , ‘\\’ ), array( DIRECTORY_SEPARATOR , DIRECTORY_SEPARATOR ), $file );
if(! is_file ( $file ) && ! is_executable ( $file ) && ! is_readable ( $file )) throw new \ Exception ( ‘O arquivo informado não foi encontrado!’ );
>
$this -> file = $file ;
$this -> set_file_info ( $this -> file );
return $this ;
>
/**
* @param str => $index = se for informado um indice é retornada uma informação específica do arquivo
*/
public function get_info ( $index = » ) if( $this -> get_file_is_called ()) if( $index === » ) return $this -> file_info ;
>
if( $index != » ) if(! array_key_exists ( $index , $this -> file_info )) throw new \ Exception ( ‘A informação requisitada não foi encontrada!’ );
>
return $this -> file_info ;
>
>
>
/**
* @todo verifica se o método get_file() foi utilizado para informar o caminho do arquivo
*/
private function get_file_is_called () if(! $this -> file ) throw new \ Exception ( ‘Nenhum arquivo foi fornecido para análise. Utilize o método get_file() para isso!’ );
return false ;
>
return true ;
>
/**
* @todo preencher a array com as infos do arquivo
*/
private function set_file_info () $this -> file_info = array();
$pathinfo = pathinfo ( $this -> file );
$stat = stat ( $this -> file );
$this -> file_info [ ‘realpath’ ] = realpath ( $this -> file );
$this -> file_info [ ‘dirname’ ] = $pathinfo [ ‘dirname’ ];
$this -> file_info [ ‘basename’ ] = $pathinfo [ ‘basename’ ];
$this -> file_info [ ‘filename’ ] = $pathinfo [ ‘filename’ ];
$this -> file_info [ ‘extension’ ] = $pathinfo [ ‘extension’ ];
$this -> file_info [ ‘mime’ ] = finfo_file ( finfo_open ( FILEINFO_MIME_TYPE ), $this -> file );
$this -> file_info [ ‘encoding’ ] = finfo_file ( finfo_open ( FILEINFO_MIME_ENCODING ), $this -> file );
$this -> file_info [ ‘size’ ] = $stat [ 7 ];
$this -> file_info [ ‘size_string’ ] = $this -> format_bytes ( $stat [ 7 ]);
$this -> file_info [ ‘atime’ ] = $stat [ 8 ];
$this -> file_info [ ‘mtime’ ] = $stat [ 9 ];
$this -> file_info [ ‘permission’ ] = substr ( sprintf ( ‘%o’ , fileperms ( $this -> file )), — 4 );
$this -> file_info [ ‘fileowner’ ] = getenv ( ‘USERNAME’ );
>
/**
* @param int => $size = valor em bytes a ser formatado
*/
private function format_bytes ( int $size ) $base = log ( $size , 1024 );
$suffixes = array( » , ‘KB’ , ‘MB’ , ‘GB’ , ‘TB’ );
return round ( pow ( 1024 , $base — floor ( $base )), 2 ). » . $suffixes [ floor ( $base )];
>
>
var_dump ((new FileInfoTool )-> get_file ( ‘sitemap.xml’ )-> get_info ());
?>
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
pathinfo
pathinfo() возвращает информацию о path в виде ассоциативного массива или строки в зависимости от options .
Список параметров
Если указан, то задает для возврата отдельный элемент: один из следующих PATHINFO_DIRNAME , PATHINFO_BASENAME , PATHINFO_EXTENSION и PATHINFO_FILENAME .
Если options не указан, то возвращаются все доступные элементы.
Возвращаемые значения
Если параметр options не передан, то возвращаемый ассоциативный массив ( array ) будет содержать следующие элементы: dirname, basename, extension (если есть) и filename.
Замечание:
Если path содержит больше одного расширения, то PATHINFO_EXTENSION возвращает только последнее и PATHINFO_FILENAME отрезает только последнее расширение. (смотрите пример ниже).
Замечание:
Если path не содержит расширения, то не будет возвращен элемент extension (см. ниже второй пример).
Если указан параметр options , будет возвращена строка ( string ), содержащая указанный элемент.
Список изменений
Версия | Описание |
---|---|
5.2.0 | Добавлена константа PATHINFO_FILENAME . |
Примеры
Пример #1 Пример использования функции pathinfo()
$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» ; // начиная с PHP 5.2.0
?>
Результат выполнения данного примера:
/www/htdocs/inc lib.inc.php php lib.inc
Пример #2 Пример с pathinfo() , показывающий разницу между null и отсутствием расширения.
$path_parts = pathinfo ( ‘/path/emptyextension.’ );
var_dump ( $path_parts [ ‘extension’ ]);
?php
$path_parts = pathinfo ( ‘/path/noextension’ );
var_dump ( $path_parts [ ‘extension’ ]);
?>
Результатом выполнения данного примера будет что-то подобное:
string(0) "" Notice: Undefined index: extension in test.php on line 6 Notice: Undefined index: extension in test.php on line 6 NULL
Примечания
Замечание:
Подробнее о получении информации о текущем пути, обратитесь к секции » Предопределенные зарезервированные переменные».
Замечание:
pathinfo() учитывает настройки локали, поэтому для корректной обработки пути с многобайтными символами должна быть установлена соответствующая локаль с помощью функции setlocale() .
Смотрите также
- dirname() — Возвращает имя родительского каталога из указанного пути
- basename() — Возвращает последний компонент имени из указанного пути
- parse_url() — Разбирает URL и возвращает его компоненты
- realpath() — Возвращает канонизированный абсолютный путь к файлу