Build PHP Extension for Multiple Versions
In this article
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
- 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. - Create a directory for your extension: Choose a descriptive name, e.g.,
myext. Navigate into it:mkdir myext && cd myext. - Generate the basic extension structure: Use the
ext_skelscript from the PHP source. If you have the PHP source, run:~/php-src/ext/ext_skel --extname=myext. This creates essential files likeconfig.m4,php_myext.h, andmyext.c. - Update config.m4 for cross-version compatibility: Open
config.m4and 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. - 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 #endifThis allows a single codebase to adapt to different internals. - 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. - 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. - Initialize the module correctly: Define the
get_module()function and ensure it returns the module entry. UseZEND_MODULE_STARTUP_D,ZEND_MODULE_SHUTDOWN_D, etc., which are aliased properly across versions. - Build the extension: Run
phpizeto generate the build environment. Then run./configure --enable-myextandmake. This compiles the extension as a shared object (.so). - Test across PHP versions: Install the extension (
make install) and enable it inphp.ini. Runphp --ri myextto verify it loads. Repeat for each PHP version you support using isolated environments. - Handle type differences: PHP 8 introduced changes like
zend_stringusage and stricter typing. Use macros likeZSTR_VAL()andZSTR_LEN()instead of direct struct access to maintain compatibility. - 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.u1instead of using accessor macros - Forgetting to run
phpizefor each PHP version when switching - Hardcoding paths or assuming specific PHP configuration
- Not testing on older versions before release
Tips
- Use
PHP_VERSION_IDchecks liberally to isolate version-specific code - Keep your extension stateless unless absolutely necessary
- Leverage
ext/standardfunctions when possible—they are stable and well-tested - Use static analysis tools like
cppcheckorclang-tidyto 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.