Forum und email

Phar archive stream and classes

Введение

The phar extension provides the phar stream wrapper and the Phar class for manipulating self-contained PHP Archive (phar) files. The Phar class can be used to create and to extract contents of phar files as well as iterating over their contents.

PHP Archive files (Phars) are special collections of files that can be transparently run right out of the file, similar to Java's jar archive files. Using a phar archive, it is possible to distribute a complete PHP application in a single file that will run out of the file without modification or extraction. Phar archives can also be used to store files for extraction similar to tar or zip archive files. Phars support compression using gzip if the zlib extension is present, and using bzip2 if the bz2 extension is present. In addition, iteration and other features are available if the SPL extension is available. Phar signature verification using md5 or sha1 is natively supported to ensure archive integrity.

The original implementation for Phar archives was in the PEAR package » PHP_Archive, and the implementation details are very similar, although the Phar extension is more full-featured. PHP_Archive has more flexibility in Phar creation, and helpful debugging tools like the PHP_Archive_Manager class, and the Phar extension supports iteration, array access, and directly manipulating Phar contents through a simple interface. PHP_Archive supports creation of Phar archives that can be processed using the Phar extension or PHP_Archive seamlessly, whereas the Phar extension is designed to create extensions that function with the Phar extension. In addition, the Phar extension will continue to work even if the allow_url_include or allow_url_fopen INI variables are disabled, while PHP_Archive-based Phar archives (without the Phar extension) will not function.

Требования

Phar requires PHP 5.2.0 or newer. Additional features require the SPL extension in order to take advantage of iteration and array access to a Phar's file contents. The phar stream does not require any additional extensions to function.

You may optionally wish to enable the zlib and bzip2 extensions to take advantage of compressed phar support.

Установка

Windows binaries may be found at » https://snaps.php.net/. To install, download php_phar.dll to the folder specified by your php.ini file's extension_dir directive. Enable it by adding extension=php_phar.dll to your php.ini and restarting your web server.

extension_dir=c:/php5/exts/
extension=php_phar.dll

Linux, BSD, and other *nix variants can be compiled using the following steps:

  • Either:

    • Run the pear installer for PECL/phar: pecl install phar
    • Copy phar.so from the directory indicated by the build process to the location specified in your php.ini file under extension_dir.
    • Add extension=phar.so to your php.ini

    Or:

    • Set the path to your php.ini via: pecl config-set php_ini /path/to/php.ini
    • Run the pear installer for PECL/phar: pecl install phar

  • Restart your web server to reload your php.ini settings.

Note: Development Versions There are currently no stable versions of PECL/phar, to force installation of the alpha version of PECL/phar execute: pecl install phar-alpha

Tip

Compiling PECL/phar without using the PEAR command

Rather than using pecl install phar to automatically download and install PECL/phar, you may download the tarball from » PECL. From the root of the unpacked tarball, run: phpize && ./configure --enable-phar && make to generate phar.so. Once built, continue the installation from step 4 above.

Дополнительная информация, такая как новый версии, скачивание, исходные файлы, информация о разработчике и CHANGELOG, могут быть найдены здесь: » https://pecl.php.net/package/phar.

Настройка во время выполнения

Поведение этих функций зависит от установок в php.ini.

Filesystem and Streams Configuration Options
Name Default Changeable Changelog
phar.readonly "1" PHP_INI_ALL  
phar.require_hash "1" PHP_INI_ALL  
phar.extract_list "" PHP_INI_ALL Available since phar 1.1.0.

Краткое разъяснение конфигурационных директив.

phar.readonly boolean

This option disables creation or modification of Phar archives using the phar stream or Phar object's write support. This setting should always be enabled on production machines, as the phar extension's convenient write support could allow straightforward creation of a php-based virus when coupled with other common security vulnerabilities.

Note: This setting can only be unset in php.ini due to security reasons. If phar.readonly is disabled in php.ini, the user may enable phar.readonly in a script or disable it later. If phar.readonly is enabled in php.ini, a script may harmlessly "re-enable" the INI variable, but may not disable it.

phar.require_hash boolean

This option will force all opened Phar archives to contain some kind of signature (currently MD5 and SHA1 are supported), and will refuse to process any Phar archive that does not contain a signature.

Note: This setting can only be unset in php.ini due to security reasons. If phar.require_hash is disabled in php.ini, the user may enable phar.require_hash in a script or disable it later. If phar.require_hash is enabled in php.ini, a script may harmlessly "re-enable" the INI variable, but may not disable it.

phar.extract_list string

Allows mappings from a full path to a phar archive or its alias to the location of its extracted files. The format of the parameter is name=archive,name2=archive2. This allows extraction of phar files to disk, and allows phar to act as a kind of mapper to extracted disk files. This is often done for performance reasons, or to assist with debugging a phar.

Example#1 phar.extract_list usage example

in php.ini:
phar.extract_list = archive=/full/path/to/archive/,arch2=/full/path/to/arch2
<?php
include "phar://archive/content.php";
include 
"phar://arch2/foo.php";
?>

Типы ресурсов

The Phar extension provides the phar stream, which allows accessing files contained within a phar transparently. The file format of a Phar is described here

Предопределенные классы

  • Phar
  • PharFileInfo
  • PharException

Using Phar Archives: Introduction

Phar archives are similar in concept to Java JAR archives, but are tailored to the needs and to the flexibility of PHP applications. A Phar archive is used to distribute a complete PHP application or library in a single file. Unlike Java's implementation of JAR archives, no external tool is required to process or run a PHP Phar archive. A Phar archive application is processed exactly like any other PHP application:

  
php coolapplication.phar
  

Using a Phar archive library is identical to using any other PHP library:

<?php
include 'coollibrary.phar';
?>

What makes Phar archives incredibly useful is the phar stream wrapper, which is explained in depth here. Using this stream wrapper, it is possible to access individual files within a phar as if the phar were its own filesystem. The phar stream wrapper supports all read/write operations on files, and opendir() on directories.

<?php
include 'phar://coollibrary.phar/internal/file.php';
header('Content-type: image/jpeg');
// phars can be accessed by full path or by alias
echo file_get_contents('phar:///fullpath/to/coollibrary.phar/images/wow.jpg');
?>

Also provided with the Phar extension is the Phar class, which allows accessing the files of the Phar archive as if it were an associative array, and other functionality. The Phar class is explained here.

<?php
try {
    
// open an existing phar
    
$p = new Phar('coollibrary.phar');
    foreach (
$p as $file) {
        
// $file is a PharFileInfo class, and inherits from SplFileInfo
        
echo $file->getFileName() . "\n";
        echo 
$file "\n"// display contents;
    
}
    if (isset(
$p['internal/file.php'])) {
        
var_dump($p['internal/file.php']->getMetaData());
    }

    
// create a new phar - phar.readonly must be 0 in php.ini
    // phar.readonly is enabled by default for security reasons.
    // On production servers, Phars need never be created,
    // only executed.
    
if (Phar::canWrite()) {
        
$p = new Phar(dirname(__FILE__) . '/newphar.phar'0'newphar.phar');
        
// create transaction - nothing is written to newphar.phar
        // until commit() is called, although temporary storage is needed
        
$p->begin();
        
// add a new file, set its contents
        
$p['file1.txt'] = 'Information';
        
$fp fopen('hugefile.dat''rb');
        
// copy from the stream
        
$p['data/hugefile.dat'] = $fp;
        if (
Phar::canCompress()) {