User Agents

Web browsers and everyday web tech, explained

Build PHP Extension for Multiple Versions

· 4 min read · Extensions

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

Building a PHP extension that runs across multiple PHP versions ensures compatibility and broad usability, especially when supporting legacy systems or targeting diverse environments. This guide walks through creating a portable, forward-compatible extension using PHP's official extension API. By following established conventions and avoiding version-specific features, you can compile and run your extension on PHP 7.4 through PHP 8.3 and beyond.

What You'll Need

  • A Unix-like development environment (Linux, macOS, or WSL on Windows)
  • PHP development headers and tools (php-dev or php-devel package)
  • GNU Autoconf, Automake, and Libtool
  • A C compiler (GCC or Clang)
  • Basic knowledge of C programming and PHP's internal structure
  • Access to multiple PHP versions for testing (via phpbrew, docker, or system packages)

Step-by-Step

  1. Set up your development environment: Install build tools and PHP development packages. On Ubuntu, use sudo apt install php-dev autoconf automake libtool build-essential. On macOS, use Homebrew: brew install php autoconf automake libtool.
  2. Create a directory for your extension: Choose a descriptive name, e.g., myext. Navigate into it: mkdir myext && cd myext.
  3. Generate the basic extension structure: Use the ext_skel script from the PHP source. If you have the PHP source, run: ~/php-src/ext/ext_skel --extname=myext. This creates essential files like config.m4, php_myext.h, and myext.c.
  4. Update config.m4 for cross-version compatibility: Open config.m4 and ensure it uses standard macros. Avoid version-specific checks unless absolutely necessary. Example:
    PHP_ARG_ENABLE(myext, whether to enable myext support,
    [  --enable-myext           Enable myext support])
    if test "$PHP_MYEXT" != "no"; then
      PHP_NEW_EXTENSION(myext, myext.c, $ext_shared)
    fi
    This keeps the build process simple and widely supported.
  5. Use PHP_VERSION_ID to conditionally compile code: In your C code, wrap version-specific logic with preprocessor checks. For example:
    #if PHP_VERSION_ID >= 80000
        // PHP 8.0+ code
    #else
        // PHP 7.x fallback
    #endif
    This allows a single codebase to adapt to different internals.
  6. Avoid deprecated or removed APIs: Use functions and macros that are stable across versions. For example, prefer ZEND_PARSE_PARAMETERS_NONE() over older parameter parsing methods. Consult the PHP documentation and source to confirm API availability.
  7. Use zend_parse_parameters() safely: This function is stable from PHP 5.3 onward. Example:
    PHP_FUNCTION(myext_hello) {
        if (zend_parse_parameters(ZEND_NUM_ARGS(), "") == FAILURE) {
            RETURN_FALSE;
        }
        RETURN_STRING("Hello from myext");
    }
    This pattern works consistently across versions.
  8. Initialize the module correctly: Define the get_module() function and ensure it returns the module entry. Use ZEND_MODULE_STARTUP_D, ZEND_MODULE_SHUTDOWN_D, etc., which are aliased properly across versions.
  9. Build the extension: Run phpize to generate the build environment. Then run ./configure --enable-myext and make. This compiles the extension as a shared object (.so).
  10. Test across PHP versions: Install the extension (make install) and enable it in php.ini. Run php --ri myext to verify it loads. Repeat for each PHP version you support using isolated environments.
  11. Handle type differences: PHP 8 introduced changes like zend_string usage and stricter typing. Use macros like ZSTR_VAL() and ZSTR_LEN() instead of direct struct access to maintain compatibility.
  12. Document supported versions: Clearly state which PHP versions your extension supports, based on testing results. Update this as new versions are released.

Common Mistakes

  • Using PHP 8-only features (e.g., JIT-related APIs) without fallbacks
  • Direct access to internal structures like zval.u1 instead of using accessor macros
  • Forgetting to run phpize for each PHP version when switching
  • Hardcoding paths or assuming specific PHP configuration
  • Not testing on older versions before release

Tips

  • Use PHP_VERSION_ID checks liberally to isolate version-specific code
  • Keep your extension stateless unless absolutely necessary
  • Leverage ext/standard functions when possible—they are stable and well-tested
  • Use static analysis tools like cppcheck or clang-tidy to catch portability issues
  • Test in minimal Docker containers to avoid dependency conflicts

Troubleshooting

If the extension fails to compile, check that the correct phpize is being used—each PHP version has its own. Run which phpize and ensure it points to the intended PHP installation. If the extension loads but functions return errors, verify parameter parsing and return value usage. Use php -d extension=myext.so -m to test loading. For segmentation faults, run PHP under gdb or valgrind to trace the crash. If the extension works in one PHP version but not another, compare config.h and check for missing conditional compilation blocks.

Frequently Asked Questions

Can I use C++ in a PHP extension?

Yes, but with caution. Use extern "C" for exported functions to prevent name mangling. However, mixing C++ exceptions with PHP’s error handling can cause instability.

How do I handle memory allocation safely?

Use emalloc(), ecalloc(), and efree() instead of standard C functions. These integrate with PHP’s memory manager and prevent leaks during request shutdown.

Do I need to support thread-safe (ZTS) builds?

Only if targeting environments like Apache with worker MPM. Most CLI and FPM setups are non-ZTS. Test both if unsure.

Can this extension work on Windows?

Yes, but the build process uses Visual Studio and phpize for Windows. Cross-compilation from Unix is not reliable; build natively or use CI with Windows runners.

How do I debug a crashing extension?

Enable core dumps, run PHP under gdb, and use bt to get a backtrace. Also, compile with -g -O0 for better debugging symbols.

Is it safe to use global variables in extensions?

No, unless declared with ZEND_BEGIN_MODULE_GLOBALS. Per-request globals are safer and prevent data leakage between requests in shared environments.