File info class php

Класс SplFileInfo

Класс SplFileInfo предоставляет высокоуровневый объектно-ориентированный интерфейс к информации для отдельного файла.

Class synopsis

public getBasename(string $suffix = ""): string
public getExtension(): string
public getFileInfo(?string $class = null): SplFileInfo
public getFilename(): string
public getLinkTarget(): string|false
public getPathInfo(?string $class = null): ?SplFileInfo
public getPathname(): string
public getRealPath(): string|false
public getType(): string|false
public openFile(string $mode = "r", bool $useIncludePath = false, ?resource $context = null): SplFileObject
public setFileClass(string $class = SplFileObject::class): void
public setInfoClass(string $class = SplFileInfo::class): void

Changelog

PHP 8.2

(PECL solr 0.9.2)Содержит методы утилиты для получения текущей версии расширения и подготовки фраз запроса.

(PHP 5 5.3.0,7,8)Класс SplDoublyLinkedList предоставляет основные функциональные возможности Список будет итерироваться в порядке last first out,подобно стеку.

(PHP 5 5.1.0,7,8)Класс SplFileObject предлагает объектно-ориентированный интерфейс для сбрасывания новых строк в конце Read при перемотке/переходе на следующую строку.

(PHP 5 5.3.0,7,8)Класс SplFixedArray предоставляет основные функциональные возможности Пример #1 Использование SplFixedArray В приведенном выше примере будет выведен результат:

Источник

SplFileInfo::setInfoClass

Use this method to set a custom class which will be used when SplFileInfo::getFileInfo() and SplFileInfo::getPathInfo() are called. The class name passed to this method must be SplFileInfo or a class derived from SplFileInfo .

Parameters

Return Values

Examples

// Define a class which extends SplFileInfo
class MyFoo extends SplFileInfo <>

$info = new SplFileInfo ( ‘foo’ );
// Set the class name to use
$info -> setInfoClass ( ‘MyFoo’ );
var_dump ( $info -> getFileInfo ());
?>

The above example will output something similar to:

See Also

User Contributed Notes 1 note

Be careful when using this method, as the functionality isn’t exactly the same as instantiating the extending class directly. This can really trip you up if you’re using type hints or instanceof checks.

class CustomFileInfo extends SplFileInfo
public function getExtension ()
$ext = strtolower ( parent :: getExtension ());

return ‘jpeg’ === $ext ? ‘jpg’ : $ext ;
>
>

$path = __DIR__ . ‘/foobar.jpeg’ ;

$good = new CustomFileInfo ( $path );

echo «» ;
var_dump ( $good instanceof SplFileInfo );
var_dump ( $good instanceof CustomFileInfo );

$bad = new SplFileInfo ( $path );
$bad -> setInfoClass ( ‘CustomFileInfo’ );

var_dump ( $bad instanceof SplFileInfo );
var_dump ( $bad instanceof CustomFileInfo );
echo «» ;

Источник

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 ());
?>

Источник

The SplFileInfo class

The SplFileInfo class offers a high-level object-oriented interface to information for an individual file.

Class synopsis

public openFile ( string $mode = «r» , bool $useIncludePath = false , ? resource $context = null ): SplFileObject

Changelog

Table of Contents

  • SplFileInfo::__construct — Construct a new SplFileInfo object
  • SplFileInfo::getATime — Gets last access time of the file
  • SplFileInfo::getBasename — Gets the base name of the file
  • SplFileInfo::getCTime — Gets the inode change time
  • SplFileInfo::getExtension — Gets the file extension
  • SplFileInfo::getFileInfo — Gets an SplFileInfo object for the file
  • SplFileInfo::getFilename — Gets the filename
  • SplFileInfo::getGroup — Gets the file group
  • SplFileInfo::getInode — Gets the inode for the file
  • SplFileInfo::getLinkTarget — Gets the target of a link
  • SplFileInfo::getMTime — Gets the last modified time
  • SplFileInfo::getOwner — Gets the owner of the file
  • SplFileInfo::getPath — Gets the path without filename
  • SplFileInfo::getPathInfo — Gets an SplFileInfo object for the path
  • SplFileInfo::getPathname — Gets the path to the file
  • SplFileInfo::getPerms — Gets file permissions
  • SplFileInfo::getRealPath — Gets absolute path to file
  • SplFileInfo::getSize — Gets file size
  • SplFileInfo::getType — Gets file type
  • SplFileInfo::isDir — Tells if the file is a directory
  • SplFileInfo::isExecutable — Tells if the file is executable
  • SplFileInfo::isFile — Tells if the object references a regular file
  • SplFileInfo::isLink — Tells if the file is a link
  • SplFileInfo::isReadable — Tells if file is readable
  • SplFileInfo::isWritable — Tells if the entry is writable
  • SplFileInfo::openFile — Gets an SplFileObject object for the file
  • SplFileInfo::setFileClass — Sets the class used with SplFileInfo::openFile
  • SplFileInfo::setInfoClass — Sets the class used with SplFileInfo::getFileInfo and SplFileInfo::getPathInfo
  • SplFileInfo::__toString — Returns the path to the file as a string

Источник

Читайте также:  Ps fsb ru general html
Оцените статью