How to Create Extensions for PHP with C/C++

Learn how to create extensions for various C/C++ libraries.


How to Create Extensions for PHP with C/C++


🔊 Knowing how to use and write PHP extensions is a critical PHP development skill that can save significant time and allow you to quickly add new features to your applications. In this video we will see how to create extensions for PHP using C/C++.


Install dependencies:

Example on Systems that use APT.

sudo apt-get install build-essential php php-dev \
              autoconf automake bison flex re2c gdb \
              libtool make pkgconf valgrind git libxml2-dev libsqlite3-dev

Create an example file with whatever name you want, example: terminalroot.cpp:

extern "C"{
   #include <php.h>
}

#define PHP_TERMINALROOT_EXTNAME "terminalroot"
#define PHP_TERMINALROOT_VERSION "0.0.1"

PHP_FUNCTION(terminalroot_php);

ZEND_BEGIN_ARG_INFO(arginfo_terminalroot_php, 0)
ZEND_END_ARG_INFO()

zend_function_entry terminalroot_php_functions[] = {
     PHP_FE(terminalroot_php, arginfo_terminalroot_php)
     {NULL, NULL, NULL}
};

zend_module_entry terminalroot_php_module_entry = {
     STANDARD_MODULE_HEADER,
     PHP_TERMINALROOT_EXTNAME,
     terminalroot_php_functions,
     NULL,
     NULL,
     NULL,
     NULL,
     NULL,
     PHP_TERMINALROOT_VERSION,
     STANDARD_MODULE_PROPERTIES
};

ZEND_GET_MODULE(terminalroot)

PHP_FUNCTION(terminalroot){
     printf("My First PHP Extension with C++\n");
}

Create an example file .m4(Autotools): config.m4, example:

PHP_ARG_ENABLE(terminalroot, Just a Basic Example of PHP Extension with C++, [ --enable-terminalroot Enable Support for this Ext])
if test "$TERMINALROOT" != "no"; then
     PHP_NEW_EXTENSION(terminalroot, terminalroot.cpp, $ext_shared)
     PHP_REQUIRE_CXX() # If you are writing in C, ignore this line
fi

To compile:

phpize
./configure --enable-terminalroot
makeup
sudo make install

Test with a PHP file and call the function created in the example: script.php:

<?php
     terminalroot_php();

Run the PHP file with the extension:

php -dextension=terminalroot script.php

Watch the video

The video is in Portuguese!


Useful links


cpp clanguage php


Share


YouTube channel

Subscribe


Marcos Oliveira

Marcos Oliveira

Software developer
https://github.com/terroo