PHP擴展開發-01:第一個擴展

<HEAD> php

   下面的操做是在Ubuntu 12.04,而且已經搭建了LAMP環境.
git

</HEAD> github


一.下載PHP源碼 sql

1.首先安裝GIT              
apache

sudo apt-get install git 

2.克隆PHP源碼 vim

cd /
git clone https://github.com/php/php-src.git
ls
會看到php-src文件夾

3.進入ext目錄 curl

cd php-src/ext
ls
會看見不少擴展如curl,pdo等,同時還會看見用來創建擴展的腳本ext_skel


二.創建骨架修改參數 函數

1.利用ext_skel創建骨架 測試

./ext_skel --extname=yourname

yourname爲你想創建的擴展的名字,咱們先建一個,例如爲rube 網站

創建好後當前文件夾下會出現rube這個文件夾

cd rube
2.修改config,m4的參數

vim config.m4

dnl Otherwise use enable:

 PHP_ARG_ENABLE(rube, whether to enable rube support,
dnl Make sure that the comment is aligned:
 [  --enable-rube           Enable rube support])

將PHP_ARG_ENABLE(rube, whether to enable rube support 和 [  --enable-rube             Enable rube support]  這兩行前面的dnl 去掉 。修改爲如上所示



三.編寫php_rube.h 和 rube.c

1.編輯php_rube.h

vim php_rube.h

  在php_rube.h的最後面添加

PHP_FUNCTION(confirm_rube_compiled);
PHP_FUNCTION(hello);
hello 爲你要建立的那個函數

2.編輯rube.c

vim rube.c

const zend_function_entry rube_functions[] = {
    PHP_FE(confirm_rube_compiled,    NULL)      
    PHP_FE(hello,    NULL)         
    PHP_FE_END  
};
  修改zend_function_entry rube_functions[] , 在PHP_FE(confirm_rube_compiled,   NULL)後面添加

 PHP_FE(hello,    NULL)

3.編寫函數

接下來編寫hello這個函數,首先編寫一個簡單的輸出"Hello my first extention"的函數。。。

   在rube.c的最後面添加

PHP_FUNCTION(hello)
{
char *arg = "Hello my first extention!";
int  len;
char *strg;

len = spprintf(&strg, 0, "%s\n", arg);
RETURN_STRINGL(strg, len, 0);
}
保存後退出



四.編譯代碼

1.編譯成so文件

cd /php-src/ext/rube
whereis phpize
看是否存在phpize

若是存在運行phpize,不然用

sudo apt-get install php5-dev 
進行安裝後運行
phpize

而後

./configure --with-php-config=你的php-config位置
若是找不到php-config的位置

whereis php-config

./configure --with-php-config=你的php-config位置
接着

make
在編譯過程當中若是你的代碼出現錯誤,會報錯。

make這步中若是提示

Build complete

說明編譯成功.而後

make install

安裝好後rube.so文件會在當前文件夾下的modules文件夾下,同時也會被安裝在系統提示的位置(也就是你的系統中php擴展的默認安裝位置),個人提示以下:

Installing shared extensions:     /usr/lib/php5/20090626+lfs/


說明rube.so被安裝在/usr/lib/php5/20090626+lfs/目錄下
ls /usr/lib/php5/20090626+lfs/  #查看是否在此文件夾下

2.修改php.ini

找到php.ini文件 而後打開在文件最後添加

extension=/usr/lib/php5/20090626+lfs/rube.so  #個人擴展在/usr/lib/php5/20090626+lfs/rube.so  你能夠相應修改

重啓apache

五.進行測試

在你網站根目錄建立test.php

vim test.php

<?php
  echo hello();
結果爲 Hello my first extention
相關文章
相關標籤/搜索