Skip to content

⚑ Native Compression (C++ FFI)

New in v2.0.3

Native C++ compressor for lightning-fast HTML/CSS/JS minification

Performance First

Supercharge your app with zero-overhead native compression. No extra PHP dependenciesβ€”just pure speed! πŸš€


🎯 Quick Setup

1️⃣ Enable FFI Extension

Edit your php.ini configuration:

ffi.enable=true
extension=ffi

Finding your php.ini

Run php --ini to locate your configuration file, or check phpinfo() output.


FFI preloading loads the native library once at server startup via OPcache, eliminating per-request FFI initialization overhead.

Create the Header File

Create a file named phpspa_compressor.h anywhere on your server (e.g. alongside your project or in a dedicated config directory):

// path to compressor library
#define FFI_LIB "/path/to/project/vendor/dconco/phpspa/src/bin/libcompressor.so"
#define FFI_SCOPE "phpspa_compressor"

char* phpspa_compress_html(const char* content, int level, int type, size_t* out_len);
char* phpspa_compress_html_esbuild(const char* content, int level, int type, const char* scope, char* debug_output, size_t* out_len);
void phpspa_free_string(char* ptr);

Path Configuration

  • FFI_LIB β€” Set this to the absolute path of the compressor shared library on your server. The library is located at vendor/dconco/phpspa/src/bin/libcompressor.so inside your project root (e.g. /var/www/myapp/vendor/dconco/phpspa/src/bin/libcompressor.so).
  • ffi.preload β€” Set this to the absolute path of the phpspa_compressor.h file you just created (e.g. /var/www/myapp/phpspa_compressor.h).

Configure php.ini

Add the following to your php.ini:

ffi.enable = "preload"
ffi.preload = "/absolute/path/to/phpspa_compressor.h"
opcache.enable = 1

Restart Required

Restart your web server (Apache/Nginx/PHP-FPM) after editing php.ini for preloading to take effect.

Verify Preloading

After restarting, check X-PhpSPA-Compression-Engine: native in your response headers to confirm the native engine is active.


2️⃣ Download Prebuilt Libraries (Optional)

PhpSPA auto-detects the compressor library from your installation. Windows and Linux binaries are included by default.

macOS Users

The macOS binary (libcompressor.dylib) is not included in the Composer package. Download it manually and configure the path:

Platform Library File Direct Link Included via Composer
Windows compressor.dll Download βœ… Yes
Linux libcompressor.so Download βœ… Yes
macOS libcompressor.dylib Download ❌ No (manual download required)

Configure custom path (macOS required):

<?php
// Set before creating the App instance
$path = __DIR__ . '/path/to/libcompressor.dylib';
putenv("PHPSPA_COMPRESSOR_LIB=$path");

$app = new \PhpSPA\App();

Or via shell environment:

export PHPSPA_COMPRESSOR_LIB="/absolute/path/to/libcompressor.dylib"

3️⃣ Force Native Mode (Optional)

To require native compression (fails if library unavailable):

<?php
// Set before creating the App instance
putenv('PHPSPA_COMPRESSION_STRATEGY=native');

$app = new \PhpSPA\App();

Or via shell environment:

export PHPSPA_COMPRESSION_STRATEGY=native

Production Recommendation

Leave this unset to enable automatic fallback to PHP compression if the native library is unavailable.


πŸ”§ How It Works

graph LR
    A[PhpSPA Request] --> B{"FFI Available?"}
    B -->|Yes| C{"Native Library Found?"}
    B -->|No| E[PHP Fallback]
    C -->|Yes| D["⚑ Native Compression"]
    C -->|No| E
    D --> F[Response]
    E --> F
Feature Description
πŸ” Auto-detect PhpSPA automatically finds the compression library in standard locations
πŸŽ›οΈ Manual override Set PHPSPA_COMPRESSOR_LIB environment variable for custom paths
πŸ” Strategy control Use PHPSPA_COMPRESSION_STRATEGY=native to enforce native-only mode
βœ… Verification Check X-PhpSPA-Compression-Engine: native in HTTP response headers

πŸ› Troubleshooting

FFI Extension Not Available

Problem: ffi.enable is not set or the extension is missing.

Solution:

# Check current PHP configuration
php -i | grep ffi

# Ensure ffi.enable=true in the correct php.ini
# Restart your web server after changes

Library Not Found

Problem: Native compressor library cannot be located.

Solution:

# Set explicit path
export PHPSPA_COMPRESSOR_LIB="/full/path/to/libcompressor.so"

# Or place library in one of these auto-detected paths inside the phpspa library:
# - vendor/dconco/phpspa/build/MinSizeRel/
# - vendor/dconco/phpspa/build/Release/
# - vendor/dconco/phpspa/build/
# - vendor/dconco/phpspa/src/bin/

Fallback Mode Active

Problem: Native compression failed; PHP fallback is being used.

Solution: Check the response header X-PhpSPA-Compression-Engine. If it shows php instead of native:

  • Verify FFI is enabled: php -m | grep FFI
  • Confirm library exists: ls -la /path/to/libcompressor.so
  • Check file permissions (must be readable by web server user)

πŸ“Š Verification

Check which compression engine handled your request:

X-PhpSPA-Compression-Engine: native
X-PhpSPA-Compression-Level: 2

πŸ’» Enable Compression in Your App

Basic Setup

<?php
use PhpSPA\Compression\Compressor;

// Enable aggressive compression with native engine
$app->compression(Compressor::LEVEL_AGGRESSIVE, true);

Compression Levels

Level Constant Description
0 LEVEL_DISABLED No compression
1 LEVEL_BASIC Remove comments only
2 LEVEL_AGGRESSIVE Basic + whitespace removal
3 LEVEL_EXTREME Aggressive + CSS/JS minification

🎨 Programmatic API

Available Methods

Minify HTML programmatically without affecting runtime configuration:

<?php
use PhpSPA\Compression\Compressor;

$html = '<div>\n  <span> Hello World </span>\n</div>';

$compressed = Compressor::compressWithLevel(
    $html, 
    Compressor::LEVEL_AGGRESSIVE
);

echo $compressed;
// Output: <div><span>Hello World</span></div>

Signature

<?php
public static function compressWithLevel(
    string $html, 
    int $level
): string

Inspect which engine handled the last compression:

<?php
use PhpSPA\Compression\Compressor;

$compressed = Compressor::compressWithLevel($html, Compressor::LEVEL_EXTREME);

$engine = Compressor::getCompressionEngine();
// Returns: 'native' | 'php' | 'disabled'

if ($engine === 'native') {
    echo "βœ… Using native C++ compression";
}

Signature

<?php
public static function getCompressionEngine(): string

Complete Example

<?php
use PhpSPA\Compression\Compressor;

$html = <<<HTML
<!DOCTYPE html>
<html>
  <head>
    <title>Test Page</title>
    <style>
      body { margin: 0; padding: 0; }
    </style>
  </head>
  <body>
    <div class="container">
      <h1>Hello World</h1>
    </div>
  </body>
</html>
HTML;

// Compress at extreme level
$compressed = Compressor::compressWithLevel($html, Compressor::LEVEL_EXTREME);

// Check engine used
$engine = Compressor::getCompressionEngine();

echo "Engine: {$engine}\n";
echo "Original: " . strlen($html) . " bytes\n";
echo "Compressed: " . strlen($compressed) . " bytes\n";
echo "Savings: " . round((1 - strlen($compressed) / strlen($html)) * 100, 1) . "%\n";

Strategy Behavior

compressWithLevel() respects PHPSPA_COMPRESSION_STRATEGY. If set to native and the library fails, an exception is thrown.


πŸ“š Additional Resources

Learn More

Full Compression Guide

Explore compression best practices, performance benchmarks, and advanced configuration options.