從零開始在 Ubuntu 12.04 (PHP 5.3.10) 建立 PHP C 擴充套件,涵蓋原始碼取得、模組骨架產生、config.m4 設定、編譯安裝、載入驗證全流程。
# 安裝必要工具
sudo apt-get install subversion php5-dev build-essential
svn checkout https://svn.php.net/repository/php/php-src/branches/PHP_5_3_10/
或使用已安裝 PHP 的原始碼目錄。
cd php-src/ext
./ext_skel --extname=my_module
會在 ext/my_module/ 產生完整骨架檔案。
編輯 ext/my_module/config.m4,找到並取消註解以下三行:
PHP_ARG_WITH(my_module, for my_module support,
[ --with-my_module Include my_module support])
cd my_module
phpize
./configure
make
sudo make install
成功會顯示:Installing shared extensions: /usr/lib/php5/20090626+lfs/
echo "extension=my_module.so" | sudo tee /etc/php5/conf.d/my_module.ini
sudo /etc/init.d/apache2 restart
<?php
// test.php
echo confirm_my_module_compiled("Hello");
// 輸出:Congratulations! You have successfully modified ext/my_module/config.m4. Module Hello is now compiled into PHP.
?>
執行 php test.php 或在瀏覽器 phpinfo() 搜尋 my_module。
編輯 my_module.c,在 PHP_FUNCTION(confirm_my_module_compiled) 後加入自訂函數:
PHP_FUNCTION(my_hello) {
php_printf("Welcome to my homepage: https://example.com");
}
並在 my_module.h 宣告,my_module.c 的 zend_function_entry 陣列註冊:
PHP_FE(my_hello, NULL)
重新 make && sudo make install 並重啟 Apache 即可使用 my_hello()。
| 問題 | 解決 |
|---|---|
| phpize 不存在 | apt-get install php5-dev |
| configure 找不到 php-config | 指定路徑 ./configure --with-php-config=/usr/bin/php-config |
| 編譯錯誤:缺少標頭檔 | apt-get install libxml2-dev libssl-dev 等相依套件 |
| 模組載入失敗 | 檢查 php -m、php -i | grep my_module、Apache 錯誤日誌 |