高速開發一個PHP擴充(SO組件)教程

來源:互聯網
上載者:User
快速開發一個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 "
";?>
  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.