Introduction
The phar:// stream wrapper is available in all PHP versions after 5.3.0. Phar stands for PHP Archive. It is used to distribute PHP application or library and is executed as a normal PHP file. The phar:// wrapper supports opening file with fopen() for read/write, rename, and directory stream operations opendir() as well as create and remove directories.
Phar class allows packaging application resources contained inside a directory in a phar archive. To perform read operations, this archive is put in phar:// wrapper
Building phar archive
To begin with, ensure that phar.readonly setting in php.ini is set to 0. Then, create a src folder in which all resources of an application are put. Create index.php file
<?php echo "phar application started"; ?>
Use object of Phar class to build phar archive containing files in src folder with buildFromDirectory() method. Specify index.php as setDefaultStub
<?php // The php.ini setting phar.readonly must be set to 0 $pharFile = 'app.phar'; // clean up if (file_exists($pharFile)) { unlink($pharFile); } if (file_exists($pharFile . '.gz')) { unlink($pharFile . '.gz'); } // create phar $p = new Phar($pharFile); // creating our library using whole directory $p->buildFromDirectory('src/'); // pointing main file which requires all classes $p->setDefaultStub('index.php', '/index.php'); // plus - compressing it into gzip $p->compress(Phar::GZ); echo "$pharFile successfully created"; ?>
Run above script from command line
php create-phar.php
This will create app.phar in working directory. To run the phar archive, use following command
php app.phar
Using phar:// wrapper
<?php echo file_get_contents('phar://app.phar/index.php'); ?>
This will display contents of index.php file