Linux下php扩展(php ext)开发记录

公司需要对通行证用户资料的教检函数封包(防止服务器沦陷,用户资料被解密),需要开发一个扩展函数,
username是cookie中的username,
hashkey 是 cookie中的 PName
开发php ext: 函数名为csdn_verify_auth,参数是username 和 hashkey ,(算法机密文件略)

第一次写PHP扩展,搜索资料到编写测试用了一天半完成,记录一下吧,以后如果需要做的话大部分时间只能浪费在C算法上。

1.先down一个php下来,编译安装:(编译环境只做测试扩展用)
<br />wget http://cn2.php.net/get/php-5.2.13.tar.gz/from/cn.php.net/mirror<br />tar zxvf php-5.2.13.tar.gz<br />cd php-5.2.13<br />./configure --prefix=/csdn_verify_auth/php --with-config-file-path=/csdn_verify_auth/php/etc<br />make ZEND_EXTRA_LIBS='-liconv'<br />make install<br />cp php.ini-dist /csdn_verify_auth/php/etc/php.ini<br />

2.修改一下vi /csdn_verify_auth/php/etc/php.ini中的extension_dir = “./”
  修改为extension_dir = "/csdn_verify_auth/php/lib/php/extensions/no-debug-non-zts-20060613"
  并在此行后增加以下,然后保存:
  extension = "csdn_verify_auth.so"
csdn_verify_auth改为你开发的扩展的名字

3.开始创建扩展项目
进入源码目录
cd /csdn_verify_auth/php-5.2.13/ext/<br />./ext_skel --extname=csdn_verify_auth

创建名字为csdn_verify_auth的项目,最终会生成csdn_verify_auth.so

4.更改配置和扩展程序开发
vi ext/csdn_verify_auth/config.m4

根据你自己的选择将

dnl PHP_ARG_WITH(csdn_verify_auth, for csdn_verify_auth support,
dnl Make sure that the comment is aligned:
dnl [ --with-csdn_verify_auth Include csdn_verify_auth support])

去掉dnl
或者将

dnl PHP_ARG_ENABLE(csdn_verify_auth, whether to enable csdn_verify_auth support,
dnl Make sure that the comment is aligned:
dnl [ --enable-csdn_verify_auth Enable csdn_verify_auth support])

去掉dnl

vi ext/csdn_verify_auth/php_csdn_verify_auth.h

PHP_FUNCTION(confirm_csdn_verify_auth_compiled); /* For testing, remove later. */
更改为
PHP_FUNCTION(csdn_verify_auth);

vi ext/csdn_verify_auth/csdn_verify_auth.c

zend_function_entry php5cpp_functions[] = {<br />PHP_FE(confirm_csdn_verify_auth_compiled, NULL) /* For testing, remove later. */<br />{NULL, NULL, NULL} /* Must be the last line in php5cpp_functions[] */<br />};
更改为
zend_function_entry php5cpp_functions[] = {<br />PHP_FE(csdn_verify_auth, NULL)<br />{NULL, NULL, NULL} /* Must be the last line in php5cpp_functions[] */<br />};
在最后添加:
PHP_FUNCTION(csdn_verify_auth)<br />{<br />zend_printf("hello world\n");<br />}

5.编译生成so文件
cd /csdn_verify_auth/php-5.2.13/ext/csdn_verify_auth/<br />/csdn_verify_auth/php/bin/phpize<br />./configure --with-php-config=/csdn_verify_auth/php/bin/php-config<br />make<br />mv /csdn_verify_auth/php-5.2.13/ext/csdn_verify_auth/modules/csdn_verify_auth.so /csdn_verify_auth/php/lib/php/extensions/no-debug-non-zts-20060613<br />cd ../../../

6.测试扩展
vi /csdn_verify_auth/hello.php

php
csdn_verify_auth();
?>

/csdn_verify_auth/php/bin/php hello.php
hello world.

OK

主要用到的api就那么几个:
ZEND_NUM_ARGS()、zend_parse_parameters(args TSRMLS_CC, “ss”, &username, &username_length, &hash, &hash_length) 参数接收系列
RETURN_FALSE。。RETURN_STRINGL(s, l, dup)等返回系列函数
…………………
其他的基本就是C了,再次感叹下,学好C语言,走到哪都不怕。

————————-END——————————