Packaging PHP libraries with PHAR

PHAR is a PHP extension providing similar support as JAR files in Java. Phar files are possibly compressed packages of any files that are used with PHP projects. This makes it possible to have all libraries along with their assets to be packed in to a single distributable file.

It is also possible to use the Pear class PHP_Archive to achieve the nearly the same functionality.

The PECL extension and the phar files can be used starting from PHP 5.2. The extension should become included by default in PHP 5.3. The php.ini settings available in “phar” extension version 2 are the following:

phar.readonly  = 1"
phar.require_hash = "1"
phar.cache_list = ""

Because of the way security is handled in the extension, which is by disabling the possibility to write phar files by default, it is best to have a local test server or particular development server where the ini setting for phar.readonly is set to Off.

By default also the phar.require_hash setting is On, therefore is wise to add signature every time a phar file is created. For maximal compatibility use sha1 hashing algorithm (Phar::SHA1). In case the “hash” extension is available and build as non shared everywhere, like it has been enabled by default as of PHP version 5.1.2, you can use stronger hashing algorithms, such as sha256 (Phar::SHA256) or sha512 (Phar::SHA512).

Even better would be if the “openssl” extension is available, thus OpenSSL signatures (Phar::OPENSSL) could be used for the best possible encryption. If the phar archive is saved as /kellivoide/piirka.phar, the public key must be saved as /kellivoide/piirka.phar.pubkey, or phar will be unable to verify the OpenSSL signature.

The setting phar.cache_list can be considered similar to the include_path setting. Difference here is that the files listed are loaded on startup for faster access times. For example:

phar.cache_list = "/kellivoide/piirka.phar:/joulupukki/tonttu.phar"

Here is an example code of creating a simple phar file of the GetID3 library:

$phar = new Phar('../libs/getid3.phar', 0, 'getid3.phar');

$files = $phar->buildFromDirectory('../libs/getid3/', '/\.php$/');

$stub = $phar->createDefaultStub();



You can then use the library as you did before but through a phar stream like this:

require_once 'phar://../libs/getid3.phar/getid3.php';

You could also do it without using the stream path (stream://) but I noticed it works easier this way. It also might be a good way always to use streams as they are the way it is done anyhow underneath.