PHP: Phar works, but compressed (.gz) doesn't

Linux howto's, compile information, information on whatever we learned on working with linux, MACOs and - of course - Products of the big evil....
Post Reply
User avatar
peter_b
Chatterbox
Posts: 383
Joined: Tue Nov 12, 2013 2:05 am

PHP: Phar works, but compressed (.gz) doesn't

Post by peter_b »

[PROBLEM]
I've created a PHP ARchive (PHAR), according to the official PHAR documentation.
The ".phar" file is created, and "bin/cinbox.php" is set as CLI and Web-Stub. So I can call it like this:

Code: Select all

$ php cinbox.phar
Awesome! :D

But if I compress the Phar file (using Phar::compress()), calling it like this:

Code: Select all

$ php cinbox.phar.gz
I get the following error:
PHP Warning: include(phar:///home/user/cinbox.phar.gz/index.php): failed to open stream: phar error: "index.php" is not a file in phar "/home/user/cinbox.phar.gz" in /home/user/cinbox.phar.gz on line 9
PHP Warning: include(): Failed opening 'phar:///home/user/cinbox.phar.gz/index.php' for inclusion (include_path='phar:///home/user/cinbox.phar.gz:.:/usr/share/php:/usr/share/pear') in /home/user/cinbox.phar.gz on line 9
The code for creating the Phar is like this:

Code: Select all

$p = new Phar($target, 0, $alias);
$p->buildFromDirectory('.', '/bin|locale/');
$p->setStub(
   $p->createDefaultStub('bin/cinbox.php', 'bin/cinbox.php')
);

if (file_exists($targetCompressed)) unlink($targetCompressed);
$p2 = $p->compress(Phar::GZ);
First, I create the Phar (uncompressed) by building it from directories, setting the default stub - and then compressing it.

[SOLUTION]
The method Phar::compress() behaves differently than I expected:
It doesn't take the properties of $p (=uncompressed Phar), but create a new one - defaulting its stub back to "index.php"!

So just move the compress() call right after the constructor, and perform the initialization on the compressed instance:

Code: Select all

$p = new Phar($target, 0, $alias);

if (file_exists($targetCompressed)) unlink($targetCompressed);
$p2 = $p->compress(Phar::GZ);

$p2->buildFromDirectory('.', '/bin|locale/');
$p2->setStub(
   $p2->createDefaultStub('bin/cinbox.php', 'bin/cinbox.php')
);
Post Reply