Zend has a darn useful tutorial on creating php extensions. After a few false starts, I’ve managed to get something working, so I’m documenting my steps here for my own future reference.
Note 1: this is specific to my Kubuntu installation.
Note 2: I’m basically refactoring Zend’s hello world example to “mytest”… just because I can.
1. create a directory for the extension. In my case I’m creating a dir “mytest” in my homedir.
2. create a phpize configuration file (config.m4) in the mytest dir:
PHP_ARG_ENABLE(mytest, whether to enable mytest support,
[ --enable-mytest Enable mytest support])
if test "$PHP_MYTEST" = "yes"; then
AC_DEFINE(HAVE_MYTEST, 1, [Whether you have mytest])
PHP_NEW_EXTENSION(mytest, mytest.c, $ext_shared)
fi
3. create the header file (php_mytest.h):
#ifndef PHP_MYTEST_H
#define PHP_MYTEST_H 1
#define PHP_MYTEST_VERSION "1.0"
#define PHP_MYTEST_EXTNAME "mytest"
PHP_FUNCTION(mytest);
extern zend_module_entry mytest_module_entry;
#define phpext_mytest_ptr &mytest_module_entry
#endif
4. Create the C file (mytest.c):
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "php.h"
#include "php_mytest.h"
static function_entry mytest_functions[] = {
PHP_FE(mytest, NULL) {
NULL, NULL, NULL}
};
zend_module_entry mytest_module_entry = {
#if ZEND_MODULE_API_NO >= 20010901
STANDARD_MODULE_HEADER,
#endif
PHP_MYTEST_EXTNAME,
mytest_functions,
NULL,
NULL,
NULL,
NULL,
NULL,
#if ZEND_MODULE_API_NO >= 20010901
PHP_MYTEST_VERSION,
#endif
STANDARD_MODULE_PROPERTIES
};
#ifdef COMPILE_DL_MYTEST
ZEND_GET_MODULE(mytest)
#endif
PHP_FUNCTION(mytest) {
RETURN_STRING("Hello World", 1);
}
5. run the command phpize to create the configure and make scripts (and associated gumpf) — you’ll have to install php5-dev if you haven’t already:
apt-get install php5-dev
6. configure, then make the module:
./configure --enable-mytest
make
7. copy the extension to your extensions dir (which is defined in /etc/php5/apache/php.ini — or in my case it doesn’t seem to be, but nonetheless appears to be the directory: /usr/lib/php5/20051025)
8. add a directive for the shared object to the php.ini file. In this case:
extension=mytest.so
9. restart apache
10. create a php script:
<?php
echo mytest();
?>
11. Point your browser at it, and hopefully you should see “Hello World”.
Which is nowhere near as painful as I thought it was going to be. Result!