React, etc. Tech Stack

React, Flux, GraphQL, Hack, HHVM...? All of this and more!

PHP FFI allows embedding raw C code in PHP scripts (PHP 7.3+)

With WebAssembly and GraalVM language runtimes and barriers are falling down. PHP is no exception with the .NET runtime now being able to excute PHP using PeachPie for high performance.

Now Dmitry Stogov from Zend has extended the realm of PHP by allowing execution of embedded C code from PHP. This will allow full access to native C functions, variables as well as data structures.

The solution, PHP FFI, is provided as an experimental extension that requires a development version of the next minor release, PHP 7.3. The solution is nowhere near for production, but it is built on a solid foundations as it is using the FFI (Foreign Functions Interface) library, libffi, which allows high level languages to generate code.

All of this is wrapped into a simple API that allows developers to write inline C code within PHP scripts:

$libc = new FFI("
    int printf(const char *format, ...);
    char * getenv(const char *);
    unsigned int time(unsigned int *);

    typedef unsigned int time_t;
    typedef unsigned int suseconds_t;

    struct timeval {
        time_t      tv_sec;
        suseconds_t tv_usec;

    struct timezone {
        int tz_minuteswest;
        int tz_dsttime;

    int gettimeofday(struct timeval *tv, struct timezone *tz);    
", "");

$libc->printf("Hello World from %s!\n", "PHP");

$tv = $libc->new("struct timeval");
$tz = $libc->new("struct timezone");
$libc->gettimeofday($tv, $tz);
var_dump($tv->tv_sec, $tv->tv_usec, $tz);

…will generate an output as follows:

Hello World from PHP!
string(135) "/usr/lib64/qt-3.3/bin:/usr/lib64/ccache:/usr/local/bin:/usr/bin:/bin:/usr/local/sbin:/usr/sbin:/home/dmitry/.local/bin:/home/dmitry/bin"
object(CData)#3 (2) {

In addition to reliability and bugs, FFI data structure access is slow at this point, it is around 4 times as slow as accessing raw PHP arrays and objects. At this stage use of FFI for speed is not feasible, but memory saving can be substancial.

Performance will improve as PHP FFI stabilizes and effort is put into optimizations. Follow PHP FFI development on GitHub:

Written by Jorgé on Thursday April 19, 2018

Permalink -

« Redux 4.0 lands with notable improvements under the hood - Drupal React.js admin update »