|
Table des matières
CXXI. Phar archive stream and classesIntroductionThe 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 if the hash extension is available. The original implementation for Phar archives was in the PEAR package PHP_Archive, and the implementation details are very similar. Pré-requisPhar requires PHP 5.2.1 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. In addition, the hash extension can be used for signing phars and verifying integrity. InstallationWindows binaries may be found at http://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 webserver.
Linux, BSD, and other *nix variants can be compiled using the following steps:
Or:
“pecl config-set php_ini /path/to/php.ini”
Des informations sur l’installation de ces extensions PECL peuvent être trouvées dans le chapitre du manuel intitulé Installation des extensions PECL. D’autres informations comme les notes sur les nouvelles versions, les téléchargements, les sources des fichiers, les informations concernant les mainteneurs ainsi qu’un CHANGELOG, peuvent être trouvées ici : http://pecl.php.net/package/phar. Configuration à l'exécutionLe comportement de ces fonctions est affecté par la configuration dans le fichier “php.ini”. Tableau 1. Filesystem and Streams Configuration Options
Voici un éclaircissement sur l’utilisation des directives de configuration. “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.
“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.
Types de ressourcesClasses pré-définies
Using Phar Archives: IntroductionPhar 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:
Using a Phar archive library is identical to using any other PHP library:
<?php include 'coollibrary.phar'; ?>
<?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'); ?>
<?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 disk until commit() is called $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()) { $p['data/hugefile.dat']->setCompressedGZ(); } $p['images/wow.jpg'] = file_get_contents('images/wow.jpg'); // any value can be saved as file-specific meta-data $p['images/wow.jpg']->setMetaData(array('mime-type' => 'image/jpeg')); $p['index.php'] = file_get_contents('index.php'); $p->setMetaData(array('bootstrap' => 'index.php')); // save the Phar, and set the loader stub $p->commit('<?php $p = new Phar(__FILE__); $m = $p->getMetaData(); require "phar://" . __FILE__ . "/" . $m["bootstrap"]; __HALT_COMPILER();'); } } catch (BadMethodCallException $e) { echo 'Could not open Phar: ', $e; } ?> Using Phar Archives: the phar stream wrapperThe Phar stream wrapper fully supports fopen() for read, write or append, unlink(), stat(), fstat(), fseek(), rename() and directory stream operation opendir(). The Phar stream wrapper does not support creating or erasing a directory, as files are stored only as files, and the concept of an abstract directory does not exist. Individual file compression and per-file metadata can also be manipulated in a Phar archive using stream contexts:
<?php $context = stream_context_create(array('phar' => array('compression' => Phar::GZ)), array('metadata' => array('user' => 'cellog'))); file_put_contents('phar://my.phar/somefile.php', 0, $context); ?> Although it is possible to create phar archives from scratch just using stream operations, it is best to use the functionality built into the Phar class. The stream wrapper is best used for read operations. Using Phar Archives: the Phar classThe Phar class supports reading and manipulation of Phar archives, as well as iteration through inherited functionality of the RecursiveDirectoryIterator class. With support for the ArrayAccess interface, files inside a Phar archive can be accessed as if they were part of an associative array. Assuming that “$p” is a Phar object initialized as follows:
<?php $p = new Phar('myphar.phar'); ?> The following is possible:
In addition, the Phar object is the only way to access Phar-specific metadata, through Phar->getMetaData(), and the only way to set or retrieve a Phar archive’s PHP loader stub through Phar->getStub() and Phar->setStub(). Additionally, compression for the entire Phar archive at once can only be manipulated using the Phar class. The full list of Phar object functionality is documented below. The PharFileInfo class extends the SplFileInfo class, and adds several methods for manipulating Phar-specific details of a file contained within a Phar, such as manipulating compression and metadata. Phar file formatAll Phar files contain three to four sections:
Phar file stubA Phar’s stub is a simple PHP file. The smallest possible stub follows: Phar::mapPhar(); include ‘phar://myphar.phar/index.php’; HALT_COMPILER(); " | There are no restrictions on the contents of a Phar stub, except for the requirement that it conclude with “HALT_COMPILER();”. The closing PHP tag “?>” may be included or omitted, but there can be no more than 1 space between the “;” and the close tag “?>” or the phar extension will be unable to process the Phar archive. Phar Manifest FormatThe Phar manifest is a highly optimized format that allows per-file specification of file compression, file permissions, and even user-defined meta-data such as user or group. All values greater than 1 byte are stored in little-endian byte order, with the exception of the API version, which for historical reasons is stored as 3 nibbles in big-endian order. All unused flags are reserved for future use, and must not be used to store custom information. Use the per-file meta-data facility to store customized information about particular files. The basic file format of a Phar archive manifest is as follows: Tableau 2. Global Phar manifest format
Global Phar bitmapped flagsHere are the bitmapped flags currently recognized by the Phar extension for the global Phar flat bitmap: Tableau 3. Bitmap values recognized
Phar manifest file entry definitionEach file in the manifest contains the following information: Tableau 4. Phar Manifest file entry
The File-specific bitmap values recognized are: Tableau 5. Bitmap values recognized
Phar Signature formatPhars containing a signature always have the signature Tableau 6. Signature format
Table des matières Phar::apiVersion – Returns the api versionPhar->begin – Begin a Phar modification transactionPhar::canCompress – Returns whether phar extension supports compression using either zlib or bzip2Phar::canWrite – Returns whether phar extension supports writing and creating pharsPhar->commit – End a Phar modification transaction by writing the Phar archive to diskPhar->compressAllFilesBZIP2 – Compresses all files in the current Phar archive using Bzip2 compressionPhar->compressAllFilesGZ – Compresses all files in the current Phar archive using Gzip compressionPhar::__construct – Construct a Phar archive objectPhar->count – Returns the number of entries (files) in the Phar archivePhar->getMetaData – Returns phar archive meta-dataPhar->getModified – Return whether phar was modifiedPhar->getSignature – Return MD5/SHA1 signature of a Phar archivePhar->getStub – Return the PHP loader or bootstrap stub of a Phar archivePhar->getVersion – Return version info of Phar archivePhar->isFlushingToPhar – Used to determine whether a Phar creation transaction is activePhar::loadPhar – Loads any phar archive with an aliasPhar::mapPhar – Reads the currently executed file (a phar) and registers its manifestPhar::offsetExists – determines whether a file exists in the pharPhar::offsetGet – get a PharFileInfo object for a specific filePhar::offsetSet – set the contents of an internal file to those of an external filePhar::offsetUnset – remove a file from a pharPhar->setMetaData – Sets phar archive meta-dataPhar->setStub – Used to set the PHP loader or bootstrap stub of a Phar archivePhar->uncompressAllFiles – Uncompresses all files in the current Phar archivePharFileInfo::__construct – Construct a Phar entry objectPharFileInfo->getCompressedSize – Returns the actual size of the file (with compression) inside the Phar archivePharFileInfo->getCRC32 – Returns CRC32 code or throws an exception if not CRC checkedPharFileInfo->getMetaData – Returns file-specific meta-data saved with a filePharFileInfo->getPharFlags – Returns the Phar file entry flagsPharFileInfo->isCompressed – Returns whether the entry is compressedPharFileInfo->isCompressedBZIP2 – Returns whether the entry is compressed using bzip2PharFileInfo->isCompressedGZ – Returns whether the entry is compressed using gzPharFileInfo->isCRCChecked – Returns whether file entry has had its CRC verifiedPharFileInfo->setCompressedBZIP2 – Compresses the current Phar entry within the phar using Bzip2 compressionPharFileInfo->setCompressedGZ – Compresses the current Phar entry within the phar using gz compressionPharFileInfo->setMetaData – Sets file-specific meta-data saved with a filePharFileInfo->setUncompressed – Uncompresses the current Phar entry within the phar, if it is compressed Travail collaboratifContribuez, en ajjoutant des elements a cette page de manuel : Merci de votre aide |