How to create PHP extensions

I use PHP for a long time now (over 15 years) but only recently I got interested in compiling my own module. Oh my ! How easy was that ?! In this small article I will add some experience to the knowldge I found on this page and try to write down a small howto about it. Enjoy !

STEP 1) Install GCC, PHP and Development package of PHP with
sudo apt-get install gcc php5 php5-dev

STEP 2) Create below two files in same directory (anywhere you want)

config.m4
PHP_ARG_ENABLE(my_extension, whether to enable my extension,
[ --enable-my-extension Enable my extension])

if test "$PHP_MY_EXTENSION" = "yes"; then
AC_DEFINE(HAVE_MY_EXTENSION, 1, [Whether you have my extension])
PHP_NEW_EXTENSION(my_extension, my_extension.c, $ext_shared)
fi

my_extension.c
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "php.h"

#define PHP_MY_EXTENSION_VERSION "1.0"
#define PHP_MY_EXTENSION_EXTNAME "my_extension"

extern zend_module_entry my_extension_module_entry;
#define phpext_my_extension_ptr &my_extension_module_entry

// declaration of a custom my_function()
PHP_FUNCTION(my_function);

// list of custom PHP functions provided by this extension
// set {NULL, NULL, NULL} as the last record to mark the end of list
static function_entry my_functions[] = {
PHP_FE(my_function, NULL)
{NULL, NULL, NULL}
};

// the following code creates an entry for the module and registers it with Zend.
zend_module_entry my_extension_module_entry = {
#if ZEND_MODULE_API_NO >= 20010901
STANDARD_MODULE_HEADER,
#endif
PHP_MY_EXTENSION_EXTNAME,
my_functions,
NULL, // name of the MINIT function or NULL if not applicable
NULL, // name of the MSHUTDOWN function or NULL if not applicable
NULL, // name of the RINIT function or NULL if not applicable
NULL, // name of the RSHUTDOWN function or NULL if not applicable
NULL, // name of the MINFO function or NULL if not applicable
#if ZEND_MODULE_API_NO >= 20010901
PHP_MY_EXTENSION_VERSION,
#endif
STANDARD_MODULE_PROPERTIES
};

ZEND_GET_MODULE(my_extension)

// implementation of a custom my_function()
PHP_FUNCTION(my_function)
{
RETURN_STRING("This is my function", 1);
}

STEP 3) Build the extension (the final product will go automatically where it suppose to be)
$ phpize
$ ./configure
$ make install

STEP 4) Add the extension to your PHP.ini. If it is for Apache2 /etc/php5/apache2/php.ini or if it is for CLI /etc/php5/cli/php.ini. Find the section Dynamic Extensions and add;
extension=my_extension.so

STEP 5) Test the extension (if Apache2; restart first)
$ php -r "echo my_function();"
This should give
This is my function

Thanks to Artur Graniszewski from Poland, now you have a PHP module ready to work on. I just copied his steps here, because I wanted in a shorter version of it. Anybody who needs the explanation should visit Arthur’s page.

Post a comment