PHP Phar context options

Phar stands for PHP Archive. All the resources of a certain PHP application or library are packaged in a single .phar file for the purpose of distribution. A phar file can be used as IO stream with phar:// wrapper.

Phar Context Options

The phar:// wrapper supports several context options for controlling compression and metadata ?

compress

PHP has predefined constants for defining compression formats ?

Constant Value Description
Phar::NONE 0x00000000 no compression
Phar::COMPRESSED 0x0000F000 bitmask to determine if any compression is present
Phar::GZ 0x00001000 zlib (gzip) compression
Phar::BZ2 0x00002000 bzip2 compression

metadata

Any PHP variable containing information to store that describes the phar archive. This is used as argument for the Phar::setMetadata() method.

Example

This example shows how to set Phar context options when creating a Phar file ?

Note: This example requires the phar extension and write permissions. It creates actual files and cannot run in an online environment.

<?php
$context = stream_context_create(array(
    'phar' => array(
        'compress' => Phar::GZ,
        'metadata' => array('user' => 'cellog')
    )
));

file_put_contents('phar://my.phar/somefile.php', '<?php echo "Hello from Phar!"; ?>', 0, $context);

echo "Phar file created with GZ compression and metadata.";
?>

Key Points

When working with Phar context options ?

  • compress − Controls file compression within the archive
  • metadata − Stores descriptive information about the archive
  • Context options are passed as an array to stream_context_create()
  • The phar extension must be enabled in PHP

Conclusion

Phar context options provide control over compression and metadata when working with PHP archives. Use the compress option to reduce file sizes and metadata to store descriptive information about your archive contents.

Updated on: 2026-03-15T09:21:58+05:30

249 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements