Building a Native Single File Binary for Your PHP Project
For a PHP CLI script there is a baseline hurdle in place for distribution - the server running the script needs to have PHP installed. While that is easier than ever, thanks in part to static PHP builds via GitHub actions - it is still an additional pain point. The simplicity of a single binary that includes the PHP interpreter bypasses that requirement.
Here are the steps I took to take Blogstream from a single PHAR, that still required PHP to be installed on your system, to a single file native binary that had no requirements. Once again the static-php-cli project has made this a surprisingly easy process.
First, I download a copy of the bulk build of php-micro from dl.static-php.dev. The bulk build includes more than 50 extensions, including the event
extension that is needed for Blogstream. They also have a common build that has 30 extensions. And you can build your own with only the exact extensions you need, for an even smaller binary.
Since I’m building this for an Apple Silicon system I’m using the macos-aarch64
build of PHP 8.4.8.
$ curl -OL https://dl.static-php.dev/static-php-cli/bulk/php-8.4.8-micro-macos-aarch64.tar.gz
$ tar -xzvf php-8.4.8-micro-macos-aarch64.tar.gz
That gives me a micro.sfx
file in the Blogstream directory.
Here is the step that impresses me with how simple it is. You concatenate micro.sfx
with bin/blogstream.phar
and then you have a native single file binary.
$ cat micro.sfx bin/blogstream.phar > bin/blogstream
$ chmod 700 bin/blogstream
At that point you can run ./bin/blogstream
and it works as expected. Concatenating micro.sfx
with your PHAR file was an elegant design decision for this process.
This isn’t limited to just PHAR files either ( though that is probably what you will want to do for any reasonably size project ) - you can also concatenate a PHP file directly. The documentation uses this example.
$ echo "<?php echo 'Hello world' . PHP_EOL;" > code.php
$ cat micro.sfx code.php > single-app && chmod +x single-app
$ ./single-app
Hello world
The micro.sfx
file is a “SelF-extracted eXecutable SAPI module”. The build from the static-php-cli project is a fork of phpmicro.
Once again I am impressed with how far the tooling for this has advanced. With only a few simple steps you can have a native single file binary for your PHP project - with the option to customize it to your specific needs.