開發一個小的php擴展

今天試了一下在php添加擴展,看了挺多資料,細節上不一致,其餘大致是差很少的。php

咱們來開發一個叫ccvita_string的函數,他的主要做用是返回一段字符,對應的php代碼可能如此:vim

function ccvita_string($str){
     $result = '<a href="'.$str.'">Link</a>'return $result;
}
即生成連接

第一步,生成代碼框架

 進入php源代碼中自帶的工具ext_skel,利用其建立文件。函數

首先咱們建立一個文件ccvita.skel,它的內容爲工具

string ccvita_string(string str)

就是告訴ext_skel這個東西,咱們要作的擴展裏面有個函數叫ccvita_string。而後執行測試

cd sofe/hongxin/src/php-5.3.27/ext/
./ext_skel --extname=ccvita --proto=ccvita.skel
cd ccvita/

這時候,ccvita這個擴展的代碼框架就已經出來了。spa

第二步,修改配置rest

vim config.m4

將十、十一、12三行最前面的dnl刪除掉,就是將code

dnl PHP_ARG_WITH(ccvita, for ccvita support,
dnl Make sure that the comment is aligned:
dnl [  --with-ccvita             Include ccvita support])

修改成blog

PHP_ARG_WITH(ccvita, for ccvita support,
Make sure that the comment is aligned:
[  --with-ccvita             Include ccvita support])

第三步,實現功能

vim ccvita.c

找到將ccvita_string這個函數修改成

PHP_FUNCTION(ccvita_string)
{
    char *str = NULL;
    int argc = ZEND_NUM_ARGS();
    int str_len;
    char *result;

    if (zend_parse_parameters(argc TSRMLS_CC, "s", &str, &str_len) == FAILURE)
        return;

    str_len = spprintf(&result, 0, "<a href=\"%.78s\">Link</a>", str);
    RETURN_STRINGL(result, str_len, 0);
}

第四步,編譯擴展
保存後,開始編譯

/usr/local/php/bin/phpize    //務必是當前運行的phpize,避免將其餘版本php執行
./configure --with-php-config=/usr/local/php/bin/php-config  //這裏須要帶上當前運行的php-config路徑
make && make install

第五步,添加擴展

這時候,一切順利的話,該擴展已經在modules/ccvita.so這個位置了。下面就是將這個擴展加入到PHP中去,讓咱們PHP程序能夠調用到。

cp modules/ccvita.so /usr/local/php/ext/
vim /usr/local/php/etc/php.ini
extension=/usr/local/php/ext/ccvita.so #在php.ini文件最後增長這一行
service php-fpm restart #重啓PHP服務
cp ccvita.php /data/www/wwwroot/default/  

接下來就能夠訪問ccvita.php這個文件,測試擴展了

直接使用

ccvita_string($str)

便可

相關文章
相關標籤/搜索