菜鳥學php擴充套件 之 hello world(一)
阿新 • • 發佈:2019-02-13
前言
這是一篇拖了很久就想寫的備忘錄,編寫php擴充套件一百度都是文章,但是很多文章是很老的了。有的例子都跑不通。有點尷尬。
此文用於記錄自己的筆記,當作備忘錄。
正文
1. 下載php安裝包
下載地址:php下載快鏈
本文選取的是php-5.6.7安裝包。
之後安裝php。
2. 建立擴充套件骨架
//跑到ext目錄
cd php-5.6.7/ext/
//執行一鍵生成骨架的操作
./ext_skel --extname=helloworld
如果看到以下提示說明建立成果
cd helloworld
ls
一下你會發現有如下檔案:
config.m4 config.w 32 CREDITS EXPERIMENTAL helloworld.c helloworld.php php_helloworld.h tests
3. 修改擴充套件的配置檔案config.m4
去掉下面程式碼之前的dnl 。(dnl相當於php的//)
##動態編譯選項,通過.so的方式連結,去掉dnl註釋
PHP_ARG_WITH(helloworld, for helloworld support,
Make sure that the comment is aligned:
[ --with-helloworld Include helloworld support])
##靜態編譯選項,通過enable來啟用,去掉dnl註釋
PHP_ARG_ENABLE(helloworld, whether to enable helloworld support,
Make sure that the comment is aligned:
[ --enable-helloworld Enable helloworld support])
一般二者選一即可(看個人喜好吧,本文教程必須去掉enable的註釋)。
4. 進行編譯測試
phpize
./configure --enable-helloworld
make
make install
然後到php.ini新增一下擴充套件
vim /usr/local/php/etc/php.ini
// 新增擴充套件
extension_dir = "/usr/local/php/lib/php/extensions/no-debug-non-zts-20131226/"
extension = "helloworld.so"
// 重啟php-fpm
/etc/init.d/php-fpm restart
回到寫擴充套件的資料夾,執行測試命令
php -d enable_dl=On myfile.php
看到如下字樣說明離勝利不遠了:
confirm_helloworld_compiled
Congratulations! You have successfully modified ext/helloworld/config.m4. Module helloworld is now compiled into PHP.
confirm_helloworld_compiled是ext_skel自動生成的測試函式。
ps:如果本地安裝了兩個php版本,並且是用php7編寫擴充套件的話,可能會遇到以下問題:
/mydata/src/php-7.0.0/ext/helloworld/helloworld.c: 在函式‘zif_confirm_helloworld_compiled’中:
/mydata/src/php-7.0.0/ext/helloworld/helloworld.c:58: 錯誤:‘zend_string’未宣告(在此函式內第一次使用)
/mydata/src/php-7.0.0/ext/helloworld/helloworld.c:58: 錯誤:(即使在一個函式內多次出現,每個未宣告的識別符號在其
/mydata/src/php-7.0.0/ext/helloworld/helloworld.c:58: 錯誤:所在的函式內也只報告一次。)
/mydata/src/php-7.0.0/ext/helloworld/helloworld.c:58: 錯誤:‘strg’未宣告(在此函式內第一次使用)
原因:編譯的環境不是php7。
解決辦法:php5 裡面沒有zend_string型別,用 char 替換,或者,修改你的php版本環境到php7
5. 建立helloworld函式
編輯helloworld.c,補充要實現的函式
##zend_function_entry helloworld_functions 補充要實現的函式
const zend_function_entry helloworld_functions[] = {
PHP_FE(confirm_helloworld_compiled, NULL) /* For testing, remove later. */
PHP_FE(helloworld, NULL) /* 這是補充的一行,尾巴沒有逗號 */
PHP_FE_END /* Must be the last line in helloworld_functions[] */
};
找到”PHP_FUNCTION(confirm_helloworld_compiled)”,另起一個函式編寫函式實體:
PHP_FUNCTION(helloworld) {
php_printf("Hello World!\n");
RETURN_TRUE;
}
再走一遍編譯:
./configure --enable-helloworld && make && make install
測試一下是不是真的成功了:
php -d enable_dl=On -r "dl('helloworld.so');helloworld();"
//輸出
Hello World!
成功!