原創 快速開發一個PHP擴充套件
快速開發一個PHP擴充套件
本文通過非常快速的方式講解了如何製作一個PHP 5.2 環境的擴充套件(PHP Extension),希望能夠在圖文的方式下讓想快速學習的朋友瞭解一下製作過程。
需求:比如開發一個叫做 heiyeluren 的擴充套件,擴充套件裡就一個函式 heiyeluren_test(),輸入一個字串,函式返回:Your input string: xxxxx。要求:瞭解C/C++程式設計,熟悉PHP程式設計環境:下載一份php對應版本的原始碼,我這裡是 php-5.2.6,先正常安裝php,假設我們的php安裝在 /usr/local/php 目錄,原始碼在 /root/soft/php/php-5.2.6/,現在開始!
步驟一:生成擴充套件框架
cd /root/soft/php/php-5.2.6/ext./ext_skel --extname=heiyelurencd /root/soft/php/php-5.2.6/ext/heiyelurenvi config.m4開啟檔案後去掉 dnl ,獲得下面的資訊:PHP_ARG_ENABLE(heiyeluren, whether to enable heiyeluren support,[ --enable-heiyeluren Enable heiyeluren support])儲存退出.(圖01)
第二步:編寫程式碼vi php_heiyeluren.h找到:PHP_FUNCTION(confirm_heiyeluren_compiled); ,新增一行:PHP_FUNCTION(heiyeluren_test);
vi heiyeluren.c數組裡增加我們的函式,找到 zend_function_entry heiyeluren_functions[],增加:PHP_FE(heiyeluren, NULL)(圖03)
再到 heiyeluren.c 檔案最後面增加如下程式碼:PHP_FUNCTION(heiyeluren_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);}儲存退出。(圖04)
第三步:編譯安裝cd /root/soft/php/php-5.2.6/ext/heiyeluren/usr/local/php/bin/phpize./configure --with-php-config=/usr/local/php/bin/php-configmakemake testmake install
現在看看是不是有個 /usr/local/php/lib/php/extensions/no-debug-non-zts-20060613/heiyeluren.so編輯php.ini,把擴充套件加入進去:vi /usr/local/php/lib/php.ini在[PHP]模組下增加:extension = heiyeluren.so儲存退出。(圖05)
注意:如果你不存在擴充套件檔案目錄,或者安裝報錯,那麼可以自行建立這個目錄,然後把擴充套件拷貝到目錄下,然後記得把 php.ini 檔案中的 extension_dir 修改為該目錄:extension_dir = "/usr/local/php/lib/php/extensions/no-debug-non-zts-20060613/"(圖06)
第四步:檢查安裝結果現在看看模組載入了沒有:/usr/local/php/bin/php -m,應該會打印出:[PHP Modules]...heiyeluren...[Zend Modules]
然後重啟apache,輸出 phpinfo() ,應該能夠看到:heiyelurenheiyeluren support enabled (圖07)
看看函式是否存在並且呼叫,在web目錄下建立:heiyeluren.php<?phpecho "<pre>";print_r(get_loaded_extensions());print_r(get_extension_funcs('heiyeluren'));echo heiyeluren_test('My first php extension');echo "</pre>";?>訪問apache,應該能夠看到:Array( ... [33] => heiyeluren)Array( [0] => confirm_heiyeluren_compiled [1] => heiyeluren_test)Your input string: heiyeluren(圖08)
擴充套件製作成功!