快速開發一個PHP擴充(SO組件)教程
本文通過非常快速的方式講解了如何製作一個PHP 5.2 環境的擴充(PHP Extension),希望能夠在圖文的方式下讓想快速學習的朋友瞭解一下製作過程。
需求:比如開發一個叫做 lanhaicode 的擴充,擴充裡就一個函數 lanhai_test(),輸入一個字串,函數返回:Your input string: xxxxx。
要求:瞭解C/C++編程,熟悉PHP編程
環境:下載一份php對應版本的源碼,我這裡是 php-5.2.17,先正常安裝php,假設我們的php安裝在 /usr/local/php 目錄,源碼在 /root/soft/php/php-5.2.17/,現在開始!
php-5.2.17下載地址:
http://blog.lrenwang.com/down/soft/php-5.2.17.tar.bz2
解壓: tar -vxjf php-5......tar.bz2
步驟一:產生擴充架構
cd /root/soft/php/php-5.2.17/ext./ext_skel --extname=lanhaicodecd /root/soft/php/php-5.2.17/ext/lanhaicodevi config.m4
開啟檔案後去掉 dnl ,獲得下面的資訊:
PHP_ARG_ENABLE(lanhaicode, whether to enable lanhaicode support,[ --enable-lanhaicode Enable lanhaicode support])
儲存退出.
第二步:編寫代碼
vi php_lanhaicode.h
找到:PHP_FUNCTION(confirm_lanhaicode_compiled); 新增一行:
PHP_FUNCTION(lanhai_test);
儲存退出。
vi lanhaicode.c
數組裡增加我們的函數,找到 zend_function_entry lanhaicode_functions[],增加:
PHP_FE(lanhaicode, NULL)
再到 lanhaicode.c 檔案最後面增加如下代碼:
PHP_FUNCTION(lanhai_test){char *arg = NULL;int arg_len, len;char *strg;if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &arg, &arg_len) == FAILURE) {return;}len = spprintf(&strg, 0, "Your input string: %s\n", arg);RETURN_STRINGL(strg, len, 0);}
儲存退出。
第三步:編譯安裝
cd /root/soft/php/php-5.2.17/ext/lanhaicode/usr/local/php/bin/phpize./configure --with-php-config=/usr/local/php/bin/php-configmakemake testmake install
./configure過程中出現如下錯誤:
checking for gcc... no
checking for cc... no
checking for cc... no
checking for cl... no
configure: error: no acceptable C compiler found in $PATH
See `config.log' for more details.
解決辦法:安裝GCC軟體套件,執行命令:
yum install -y gcc
現在看看是不是有個 /usr/local/php/lib/php/extensions/no-debug-non-zts-20060613/lanhaicode.so
編輯php.ini,把擴充加入進去:
vi /usr/local/php/lib/php.ini
在[PHP]模組下增加:
extension = lanhaicode.so
儲存退出。
注意:如果你不存在擴充檔案目錄,或者安裝報錯,那麼可以自行建立這個目錄,然後把擴充拷貝到目錄下,然後記得把 php.ini 檔案中的 extension_dir 修改為該目錄:
extension_dir = "/usr/local/php/lib/php/extensions/no-debug-non-zts-20060613/"
第四步:檢查安裝結果
現在看看模組載入了沒有:
/usr/local/php/bin/php -m,應該會列印出:
[PHP Modules]
...
lanhaicode
...
[Zend Modules]
然後重啟apache,輸出 phpinfo() ,應該能夠看到:
lanhaicode
lanhaicode support enabled
看看函數是否存在並且調用,在web目錄下建立:lanhaicode.php
";print_r(get_loaded_extensions());print_r(get_extension_funcs('lanhaicode'));echo lanhai_test('My first php extension');echo "";?>