February 2020 Summaries
2 posts from Upsun
Filter
Month:
Year:
Post Summaries
Back to Blog
PHP's Foreign Function Interface (FFI), introduced in PHP 7.4, allows PHP to call C libraries, providing a bridge between PHP and C code. This feature is particularly useful for leveraging existing C libraries or performing heavy computational tasks more efficiently than PHP alone could handle. However, FFI poses security risks, especially in web environments, so it's enabled by default only for the PHP CLI. To use FFI effectively, developers must manually enable opcache, which is required for FFI to function in CLI mode. Preloading, a new feature in PHP 7.4, can be used to load C libraries into PHP-FPM's memory, reducing initialization overhead for web requests. This process involves creating a header file to expose only the desired parts of the library to PHP, using FFI::cdef() or FFI::load() to initialize the library, and leveraging preloading to improve performance. While FFI can be cumbersome and often slower for trivial tasks, it offers significant advantages for CPU-intensive operations or when integrating extensive pre-existing C libraries, although careful management of the API and security considerations are crucial.
Feb 26, 2020
2,581 words in the original blog post.
PHP 7.4 introduced Foreign Function Interface (FFI), which allows PHP developers to integrate code from other languages, particularly C, more easily than by writing an extension, though it still requires some effort. The process involves creating a shared library from C code, which can be accessed by PHP during runtime. This post details the creation of a simple C library that calculates the distance between two points using the Pythagorean Theorem, demonstrating the steps of compiling C source files into object files, linking them into an executable, and creating a shared library suitable for PHP FFI. The C program construction process is explained, including the use of header files for defining interfaces and the use of a Makefile to automate the build process, highlighting essential commands and conventions within C programming. The ultimate goal is to prepare the necessary components—specifically the shared object and header files—for integration with PHP's FFI, providing a foundation for PHP developers looking to leverage the performance benefits of C within their PHP applications.
Feb 20, 2020
1,919 words in the original blog post.